esbuild-plugin-environment

raw JSON →
0.5.0 verified Mon Apr 27 auth: no javascript

esbuild plugin that replaces process.env references with environment variable values at build time. Supports both object maps (key → default value) and arrays of keys. Version 0.5.0 is the latest stable release, with active maintenance. Key differentiators: simple API, supports both Node.js and browser targets, ships TypeScript definitions, and integrates seamlessly with esbuild's plugin system. The plugin is lightweight and focuses exclusively on environment variable injection, unlike more complex solutions like dotenv or webpack's DefinePlugin.

error ReferenceError: __esbuild_plugin_environment is not defined
cause Misconfigured environmentPlugin or alternative plugin interference
fix
Ensure environmentPlugin is the first plugin in the plugins array
error Error: [plugin: environment-plugin] Cannot find module 'process'
cause Missing process polyfill in browser builds
fix
Add inject plugin with process polyfill instead of environmentPlugin for browser targets
breaking Requires esbuild >= 0.15 for peer dependency compatibility
fix Upgrade esbuild to version 0.15 or higher
breaking CommonJS require() may fail due to ESM-only export in v0.5.0
fix Use dynamic import or switch project to ESM
deprecated Node.js <20 is no longer supported
fix Upgrade Node.js to 20 or later
gotcha environmentPlugin replaces process.env references literally; does not read actual process.env at build time for array keys
fix Pass object map with fallbacks or ensure environment variables are set before build
gotcha npm packages may have their own process.env usage that gets inappropriately replaced in bundled output
fix Use esbuild's external or exclude plugin for specific dependencies
npm install esbuild-plugin-environment
yarn add esbuild-plugin-environment
pnpm add esbuild-plugin-environment

Shows ESM usage with object map: defines API_URL (with fallback) and NODE_ENV as build-time constants.

import { environmentPlugin } from 'esbuild-plugin-environment';
import * as esbuild from 'esbuild';

await esbuild.build({
  entryPoints: ['app.ts'],
  bundle: true,
  outfile: 'out.js',
  plugins: [
    environmentPlugin({
      API_URL: process.env.API_URL ?? 'http://localhost:3000',
      NODE_ENV: 'production',
    }),
  ],
});