Webpack configuration for multiple environments : different ways
I had searched much on direct & easy ways of webpack configuration for multiple environments. I was not able to find a straight forward article and hence I’m writing about it.
To configure webpack manually for multiple environments (say dev/prod), we can do it in the following ways,
- Configure in a single file
- Configure in multiple files
Below is the difference between the both,
Single File Configuration | Multi File Configuration | |
---|---|---|
When to use? | can be used when only few config properties between env differ. |
can be used when most of the config properties between env differ. |
No of config files | single file for all env eg: webpack.config.js |
mutiple files used. One file for each env. eg: dev.js, prod.js |
config definition | config declared as function & env is passed |
2.a) config declared as obj 2.b). config declared as fn -official link |
package.json (script command) |
webpack –env= <env> | 2.a) webpack –config=<filepath/filename> 2.b) webpack –env= <env> |
Disadvantage | code-cluttering increases with increase in different values for same config properties across env. |
repeatability of common env config properties across files. |
Therefore based on one’s project scope and need, one can choose which approach to go with.
Approach 1: Single File Configuration:
webpack.config.js:
Note: config is declared as a function with environment param.
package.json:
Add the below in the scripts section,
In the above command, --env
tag passes environment as ‘development’ / ‘production’ to webpack’s config function.
Approach 2: Multi File Configuration:
Here separate files are created for each environment.
Note: Here config is declared as an object.
Approach 2.a) package.json:
In the above command, --config
refers to the config-file-path .
Default file path is webpack.config.js or webpackfile.js
Other approaches:
- Approach 2.b) Invoke respective env files from webpack.config.js as given in official link (Manual way)
- webpack.config.js: Here config is declared as function. Respective env config files are invoked based on env.
- package.json:
webpack --env = <env>
- Automatic configuration for production:
webpack -p
. Official link
It was be nice to have all these examples in git or any repo for readers to clone and try it out.
I didn’t find this kind of write up even on the official blog site.
Prem
April 17, 2017 at 6:26 PM
Thanks Prem. I haven’t hosted one yet in github. For the next blog I will host it and share the link.
thangaveluaishwarya
May 28, 2017 at 11:52 PM
Nice article👍
Thanks for putting up in a blog
Ajnin
April 22, 2017 at 7:27 AM