ghuntheur
ghuntheur

Reputation: 392

Get variable mode development or production in webpack 4

I'm using Webpack 4 and I want to use env environment variable in config. How I get this variable with mode --development and --production ? DefinePlugin doesn't work and documention says nothing.

Upvotes: 1

Views: 4145

Answers (2)

rzymek
rzymek

Reputation: 876

OP was asking about webpack4. In webpack4 one can use --mode argument which automatically sets mode in webpack config.

How to use mode inside webpack config?

An example way of passing mode to webpack-cli:

"scripts": {
  "start:dev": "webpack --mode development --watch"
}

in webpack config you can use 2nd parameter argv to access arguments:

module.exports = (env, argv) => ({
...
   watch: argv.mode !== 'production',
...
})

update

If you use IDE that reads webpack config (e.g. Intellij IDEA) you may need to pass some default value for argv:

module.exports = (env, argv = {}) => ({

in order to have valid config even if IDE doesn't pass argv (in my case, I needed it for a support of webpack alias module resolution in IDE).

update2

Another thing is babel config. Maybe it's a less known fact but babel and its presets and plugins can react on NODE_ENV (it's configurable as well), for example you can configure development option of @babel/preset-react (https://babeljs.io/docs/en/babel-preset-react#development). In order to do that you still need to set NODE_ENV (by default or sth else if you modified babel.config.js) before running webpack.

Why? The only things that --mode does are 1) the value is available via argv.mode in your config 2) sets NODE_ENV via DefinePlugin for your bundles however NODE_ENV is not set for webpack config itself nor loaders.

Finally, you can use the following if you want the consistency between bundling environment and generated bundles:

cross-env NODE_ENV=production webpack --mode production

Upvotes: 2

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36199

Maybe you could do something like this:

package.json:

"scripts": {
  "dev": "webpack-dev-server --config webpack.config.js --env.NODE_ENV=development",
  "build": "webpack --config webpack.config.js --env.NODE_ENV=production"
},

webpack.config.js:

module.exports = (env) => {
  return {
    mode: env.NODE_ENV,
    // ...rest of config based on environment
  };
};

more on passing environmental variables to config.

Upvotes: 1

Related Questions