How to use multiple configuration files in webpack?

Kousher Alam picture Kousher Alam · Mar 8, 2018 · Viewed 11.9k times · Source

I'm building a webpack automated workflow. I completed the development server. All of my development configurations are in webpack.config.js file.

Then, I add it into package.json script via 'dev':'webpack-dev-server'

How would one make a configuration for production in a separate file?

Answer

Carloluis picture Carloluis · Mar 8, 2018

There are some ways to accomplish that. Perhaps the simplest one is specifying the config file to use. Read more about webpack usage with config file.

Add another script in your package.json with:

"build": "webpack --config ./path-to/webpack.config.prod.js"

Place your production config object inside webpack.config.prod.js.


Another way is using the npm lifecycle event. Update your current webpack.config.js script to check the target script and decide which config to use:

const TARGET = process.env.npm_lifecycle_event;
if (TARGET === 'dev') {
   module.exports = require('./path-to/webpack.config.dev.js');
}
if (TARGET === 'build') {
   module.exports = require('./path-to/webpack.config.prod.js');
}

You can find previous approach in this webpack-demo project on GitHub.