Here’s what most people that worked with Webpack would agree: setting it up is not exactly a walk in the park, especially if you are trying to do multiple things at once like transpiling from ES6, using hot reloading and proxying your backend. But that’s what I am trying to change with this article.

We are going to use the application we built in the previous article and add HMR to it. First of all, in order to use Hot Module Reloading in Webpack we must use the Webpack Dev Server which is essentially a Node / Express wrapper. Second, the HMR module doesn’t do a whole lot unless we are able to take advantage of it, and this is where the React HMR module comes in. Third, because we want to use ES6, we’ll be using the babel-es2015-preset and we will be configuring a loader for Webpack. Also we are going to use Babel to transpile the .jsx syntax.

Webpack at its core is just a module bundler. It essentially detects dependencies between the building blocks of your application (like code files, style files etc.) and creates a bundle out of everything.

image-title-here

It doesn’t actually do things like transpilation — if you have Coffee-script code, Typescript or ES6 code, you will have to use a loader. We will be using babel-loader to compile our ES6/jsx code and feed it into Webpack.


image-title-here


On the other side of the chain there are plugins like uglifyJS (which we’re not using in the code sample, but I’ve added it in the drawing as an example of a plugin), which is a Javascript minifier. Another plugin example is webpack-dev-server which we will be using to implement hot reloading.

Let’s Jump Right In

The dependencies section of the package.json file look like this:

Our .babelrc file looks like this:

And finally, let’s have a look at the Webpack configuration page.


Adding Hot Reloading

Webpack Hot Module Replacement works by adding a small runtime to the generated bundle (which is going to run alongside your app) that constantly communicates with the server and if part of the dependency tree changes, it will inject the new dependencies. However, in order for this process to take place, we need to setup the Webpack Development Server, which means we need to add the following lines of code in the webpack.config.js file in the configuration object.

plugins: [
  new webpack.HotModuleReplacementPlugin()
],
devServer: {  
  proxy: {
    '*': 'http://localhost:3000'
  },
  hot: true,
  contentBase: './src/static',
  port: 9000   
}

Second, we actually need React to do something when the bundle changes, which is where the react-hot-loader package comes into play. A module can only be updated if you “accept” it. So you need to module.hot.accept() the module in the parents or the parents of the parents.

Have a look at the following code:

You can find the source code here.