DEV Community

Austin Spivey for Wia

Posted on

How to set up different Webpack configurations for development and production

A common requirement with web applications is a different build process for development and production. This is easily achievable with task runners such as Gulp or Grunt, but with Webpack you'll need to take a different approach. Here I'll show you the most straight forward method I've found.

First, create 3 files:
webpack.config.dev.js: This will be your Webpack config for development
webpack.config.prod.js: This will be your Webpack config for production
webpack.config.js: This will be your main Webpack config

The contents of webpack.config.js should be simply this:

module.exports = (env) => {
  return require(`./webpack.config.${env}.js`)
}
Enter fullscreen mode Exit fullscreen mode

Now the webpack command will take an argument env, which tells it which config file to use.

Next, populate your dev and prod config files as you normally would your webpack.config.js. In webpack.config.dev.js you may want to run a dev server and inline all your styles, while in webpack.config.prod.js you may want to extract your styles to a CSS file, uglify your JS, and deploy your build directory to a server.

Now you can run webpack --env=dev or webpack --env=prod to run the respective webpack configs.

If you find that a lot of your configuration is duplicated between the two, you could create a fourth file called webpack.config.base.js or similar. In this file, set up your webpack config with all the rules that apply to both development and production. In your dev and prod config files, only include the rules that apply to that environment.
In order to merge the base config into the others, you'll need webpack-merge.

npm install webpack-merge

In webpack.config.dev.js and webpack.config.prod.js, include the following at the top of the file:

const merge = require('webpack-merge');
const baseConfig = require('./webpack.config.base.js');
Enter fullscreen mode Exit fullscreen mode

...and change

module.exports = {
  ...
};
Enter fullscreen mode Exit fullscreen mode

to

module.exports = merge(baseConfig, {
  ...
});
Enter fullscreen mode Exit fullscreen mode

Now you can run the same commands as above, and the base config will be merged into the others.

Top comments (1)

Collapse
 
kmwarter profile image
Keith Warter

Why not just use something like, "buildDev": "webpack --config dev.config.js", "buildProd": "webpack --config prod.config.js" instead of having that third file that just allows you to pass in the env using --env?