webpackwebpack-5

NODE_ENV and mode in webpack 5


In webpack 4, I was able to specify different values for NODE_ENV and webpack mode. In my application, I am using NODE_ENV to indicate the environment with possible values of local, development, qa, staging, and production. Separately, I was setting mode in webpack to control optimizing my bundle. If my environment was staging or production, I would set the webpack mode to production, else it would use development.

In webpack 5, this does not seem possible. When I simply try to upgrade webpack from 4 to 5 and run my application, I get the following warning:

enter image description here

"local"' !== '"development"

My DefinePlugin is defined as follows:

plugins: [
  new webpack.DefinePlugin({
    'process.env': {
      NODE_ENV: process.env.NODE_ENV ?? '',
      ...variablesFromEnvironmentJsonConfig
    }
  }),
  ...
]

And I define mode in the config as follows:

mode: shouldOptimizeBundle ? 'production' : 'development',

So it appears webpack 5 has a problem when NODE_ENV does not equal mode. Webpack 5's documentation says the supported values for mode are development, production, and none. Then, confusingly, it says "If mode is not provided via configuration or CLI, CLI will use any valid NODE_ENV value for mode."

Ideally, I'd be able to continue doing what I do in webpack 4 which is have optimization and environment not be dependent of each other. In webpack 5, is it possible to have NODE_ENV be different than mode?


Solution

  • I believe the config you want is optimization.nodeEnv.

    From the docs: https://webpack.js.org/configuration/optimization/#optimizationnodeenv

    optimization.nodeEnv

    boolean = false string

    Tells webpack to set process.env.NODE_ENV to a given string value.

    optimization.nodeEnv uses DefinePlugin unless set to false.

    optimization.nodeEnv defaults to mode if set, else falls back to 'production'.

    Possible values:

    any string: the value to set process.env.NODE_ENV to.

    false: do not modify/set the value of process.env.NODE_ENV.

    webpack.config.js

    module.exports = {
      //...
      optimization: {
        nodeEnv: 'production',
      },
    };
    

    Tip

    When mode is set to 'none', optimization.nodeEnv defaults to false.

    This is probably what causes the warning:

    optimization.nodeEnv defaults to mode if set, else falls back to 'production'.

    I believe setting this config to false will eliminate the warning, although the description seems to have conflicting statements.