Node Env Webpack Plugin

raw JSON →
2.0.0 verified Sat Apr 25 auth: no javascript

Simplifies NODE_ENV handling in webpack builds. Current stable version 2.0.0 (2024), requires Node.js >=18 and is pure ESM. Sets process.env.NODE_ENV automatically: defaults to 'development' at import time if undefined, or 'production' when webpack runs with -p. Provides convenience boolean getters (isProduction, isDevelopment, isTest) to avoid typos, and a devtool helper that selects source-map in production and cheap-module-source-map in development. Replaces manual NODE_ENV checks and webpack.EnvironmentPlugin setup with a single plugin.

error require() of ES Module ... from ... not supported
cause Using CommonJS require() on an ESM-only package.
fix
Switch to import syntax (import NodeEnvPlugin from 'node-env-webpack-plugin') or use dynamic import() if needed.
error Cannot find module 'node-env-webpack-plugin'
cause The package is not installed or Node.js version is <18 (v2 requires Node.js 18).
fix
Run 'npm install node-env-webpack-plugin' and ensure Node.js >=18.
breaking v2.0.0 dropped support for Node.js <18 and is now pure ESM. CommonJS require() will throw.
fix Use import instead of require, and ensure Node.js >=18.
breaking v2.0.0 stopped supporting webpack <5. The plugin only works with webpack 5+.
fix Upgrade to webpack 5.
gotcha NODE_ENV is set at import time, not when the plugin is instantiated. If you import the plugin but then change process.env.NODE_ENV before webpack processes the config, the plugin's static properties are based on the initial value.
fix Set NODE_ENV before importing the plugin or use explicit webpack mode.
gotcha The plugin does not override NODE_ENV if it's already set. It only sets it when undefined at import time.
fix If you need to force a specific NODE_ENV, set it explicitly in the environment.
npm install node-env-webpack-plugin
yarn add node-env-webpack-plugin
pnpm add node-env-webpack-plugin

Minimal webpack config using NodeEnvPlugin to auto-set NODE_ENV and configure devtool based on environment.

// webpack.config.js
import NodeEnvPlugin from 'node-env-webpack-plugin';

export default {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js'
  },
  devtool: NodeEnvPlugin.devtool,
  plugins: [
    new NodeEnvPlugin()
  ]
};