Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple configuration files in webpack?

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?

like image 684
Kousher Alam Avatar asked Mar 08 '18 08:03

Kousher Alam


People also ask

Can you have multiple webpack config files?

The npm module webpack-merge is a confortable way of having multiple configuration files in webpack. It allows to have a common configuration file and several other that "extend" from this one as the following example will show. This would be where the common configurations between your other files are.

Can webpack have multiple entry points?

webpack.config.jsWe can also pass an array of file paths to the entry property which creates what is known as a "multi-main entry". This is useful when you would like to inject multiple dependent files together and graph their dependencies into one "chunk".

Is it mandatory to use a configuration file when setting up a webpack project?

Out of the box, webpack won't require you to use a configuration file. However, it will assume the entry point of your project is src/index. js and will output the result in dist/main.


1 Answers

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.

like image 115
Carloluis Avatar answered Oct 23 '22 18:10

Carloluis