Get current `--mode` in webpack.config.js

Solution 1:

You want to avoid duplication of options passed on the script.

When you export a function, the function will be invoked with 2 arguments: an environment env as the first parameter and an options map argv as the second parameter.

package.json

"scripts": {
  "build-dev": "webpack --mode development",
  "build-prod": "webpack --mode production"
},

webpack.config.js

module.exports = (env, argv) => {
    console.log(`This is the Webpack 4 'mode': ${argv.mode}`);
    return {
        ...
    };
}

These are the results:

For npm run build-dev:

> webpack --mode development

This is the Webpack 4 'mode': development
Hash: 554dd20dff08600ad09b
Version: webpack 4.1.1
Time: 42ms
Built at: 2018-3-14 11:27:35

For npm run build-prod:

> webpack --mode production

This is the Webpack 4 'mode': production
Hash: 8cc6c4e6b736eaa4183e
Version: webpack 4.1.1
Time: 42ms
Built at: 2018-3-14 11:28:32

Solution 2:

To test if is in production mode, inside webpack.config.js file I use this:

const isProduction = process.argv[process.argv.indexOf('--mode') + 1] === 'production';

const config = {
    ...
};

if (isProduction) {
    config.plugins.push(new MiniCssExtractPlugin());
} else { // isDev
    config.devtool = /*'source-map'*/  'inline-source-map';
}

module.exports = config;

Stop trying NODE_ENV, is old school ( webpack 3 ).

And this is more compatible to work with import / webpack resolver