Search code examples
webpackwebpack-4

Webpack v4 — how to access 'mode' option value


Webpack v4 has introduced two sets of defaults: production and development. My question is: Is there a way to refer to those inside a configuration file? I know I can still pass environment variables as:

--env.NODE_ENV=development

by doing this I have two independent environment variables and this doesn't feel right. Another option would be obviously to refer to a different config file and this doesn't look like an optimal solution for simple configurations as well.

Am I missing something here?


Solution

  • Found a better way in a webpack github issue. Since webpack 2 you can export a function in webpack.config.js, the parsed argv will be passed to that function.

    For webpack 4 you can write the config like:

    // webpack.config.js
    module.exports = (env, argv) => {
        console.log(argv.mode);
        return { /* your config object */ };
    };
    
    // $webpack-cli --mode development
    // development
    

    Original Answer:

    You can use some libs like minimist to parse the arguments passed by the cli:

    // webpack.config.js
    const args = require('minimist')(process.argv.slice(2));
    console.log(args.mode);
    
    // $webpack-cli --mode development
    // development