Besides exporting a single configuration object, there are a few more ways that cover other needs as well.
Eventually you will find the need to disambiguate in your webpack.config.js
between development and production builds. You have (at least) two options:
One option is to export a function from your webpack configuration instead of exporting an object. The function will be invoked with two arguments:
argv
) as the second parameter. This describes the options passed to webpack, with keys such as output-filename
and optimize-minimize
.-module.exports = {
+module.exports = function(env, argv) {
+ return {
+ mode: env.production ? 'production' : 'development',
+ devtool: env.production ? 'source-map' : 'eval',
plugins: [
new TerserPlugin({
terserOptions: {
+ compress: argv['optimize-minimize'] // only if -p or --optimize-minimize were passed
}
})
]
+ };
};
webpack will run the function exported by the configuration file and wait for a Promise to be returned. Handy when you need to asynchronously load configuration variables.
It is possible to export multiple promises by wrapping them into
Promise.all([/* Your promises */]).
module.exports = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
entry: './app.js',
/* ... */
});
}, 5000);
});
};
Returning a
Promise
only works when using webpack via CLI.webpack()
expects an object.
Instead of exporting a single configuration object/function, you may export multiple configurations (multiple functions are supported since webpack 3.1.0). When running webpack, all configurations are built. For instance, this is useful for bundling a library for multiple targets such as AMD and CommonJS:
module.exports = [{
output: {
filename: './dist-amd.js',
libraryTarget: 'amd'
},
name: 'amd',
entry: './app.js',
mode: 'production',
}, {
output: {
filename: './dist-commonjs.js',
libraryTarget: 'commonjs'
},
name: 'commonjs',
entry: './app.js',
mode: 'production',
}];
If you pass a name to
--config-name
flag, webpack will only build that specific configuration.