loading...
Wia

How to set up different Webpack configurations for development and production

anspivey profile image Austin Spivey ・2 min read

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`)
}

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');

...and change

module.exports = {
  ...
};

to

module.exports = merge(baseConfig, {
  ...
});

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

Posted on by:

anspivey profile

Austin Spivey

@anspivey

Tourist in a Tutu || Chicago Born || Melbourne/Mexico/California Raised || New Yorker at Heart || SF to Dublin to work for Wia the best #IoT startup

Wia

Wia is where people and things go to talk. Our mission is to make it possible for anyone to connect anything to the Internet, creating the next generation of the physical web. Developers across the world use Wia to build out IoT Solutions.

Discussion

pic
Editor guide
 

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?