3 Ways to Set Up Webpack with HMR

November 6th, 2015

It's not clear in the Webpack documentation, but there are exactly 3 ways that you can set up Webpack's hot module replacement (HMR) feature.

If you aren't sure what HMR is or why you should be using it, jump over to my why use HMR post. It could become one of those tools that saves you so much time, you wish you knew about it months ago.

The 3 Ways

Let's jump right into the 3 ways. These are ordered from the simplest setup to the most complex, but none of them are that complicated. The hardest part is picking which approach is right for you.

1. webpack-dev-server CLI

Run the webpack-dev-server on the command-line. With this approach you often don't need to change your webpack.config.js file, so it's the simplest. WDS CLI Docs.

2. webpack-dev-server API

Run WebpackDevServer from a node.js script. Requires some additions to your webpack.config.js. WDS API Docs.

3. webpack-hot-middleware w/ express

webpack-hot-middleware is a really useful tool for incorporating a webpack dev server with hot reloading into an express server. Details in the webpack-hot-middleware github repository.

But how do I choose?

I've put together a short set of criteria for how you can pick which approach is right for your project.

  • If you want the simplest possible setup: use the webpack-dev-server CLI. It requires no configuration.

  • If you are using a task runner like grunt or gulp you'll want to use the webpack-dev-server API. You can run the server from one of your tasks.

  • Or similarly, if you have your own node scripts to run webpack, you'll want to use the webpack-dev-server API.

  • If you want to use express to host your site, it is very convenient to use webpack-hot-middleware. It will be integrated with your express server, so you won't have to run another server for your bundled JS.

Okay, I picked one, but how do I start?

Glad you asked! I set up a github repository just for you. In ahfarmer/webpack-hmr-3-ways I have created a starter project for each of the 3 ways. So whichever approach you've picked, you can get up and running quickly. Each project has a README and lots of comments to explain what's going on.

BTW, are you the type of person who wants to actually know how things work before you use them? I wrote an article on understanding HMR that might interest you. It even has a sweet diagram.