Passing command line arguments to webpack.config.js

I have a simple webpack.config.js

module.exports = {
  entry: "./app.js",
  output: {
    filename: "bundle.js"
  },
}

And I want to pass the values for entryand output through command line arguments. Is that possible and how would I do that?


webpack.config.js can also exports a function of env which can return a conf object. You can therefore have a webpack config like:

module.exports = env => {
    return {
        entry: env === "production" ? "./app.js": "app-dev.js",
        output: {
          filename: "bundle.js"
        },
    }
};

and then call webpack from command-line (or package.json) like this:

webpack --env=production

You can provide custom parameters by passing environment variables on the command line. The syntax for this has changed between version 4 and 5 of Webpack. For this example, you would call:

For Webpack 5:

webpack --env entry='./app.js' --env output='bundle.js'

For Webpack 4:

webpack --env.entry='./app.js' --env.output='bundle.js'

For both versions, you can then access the environment variables in your Webpack config by doing

module.exports = env => ({
  entry: env.entry,
  output: {
    filename: env.output
  },
});

You can also pass multiple key-value pairs to you config using --env=key=value:

webpack --env=mode=production --env=branch=develop

or (for development with webpack-dev-server):

webpack serve --env=mode=production --env=branch=develop

webpack.config.js would look like this:

module.exports = (env) => {
  const mode = env.mode === 'prod' ? 'dev';
  const branch = env.branch ? env.branch : 'develop';

  return {
    entry: mode === 'prod' ? './app.js': 'app-dev.js',
    output: {
      filename: 'bundle.js',
      path: 'dist/' + branch),
    },
  }
}

All values passed this way are available as an object in the config which makes it easy to use them.

{ 
  WEBPACK_BUNDLE: true,
  mode: 'production',
  branch: 'feature-x',
  foo: 'bar'
}

You can use the --env CLI argument to pass arbitrary parameters to the config.

For example, the following command:

webpack --env entry=./entry.js --env output=./output.js

Will produce the following env object:

{entry: './entry.js', output: './output.js'}

Which you can then use in your config like so:

module.exports = env => ({
  entry: env.entry,
  output: {
    filename: env.output
  },
});

Read more here: Webpack - Environment Variables


You may use argv package and set the variables. You must do it before module.export.