Passing command line arguments to webpack.config.js
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'
}
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
},
});