Adding Hot Module Replacement (HMR) to Webpack

Adding Hot Module Replacement (HMR) to Webpack

Once you have set up webpack and Babel to develop d3.js you might want to enable hot module replacement (HMR) so that you do not have to refresh the browser every time you make a change. First, in your root folder, create a file named webpack.config.js and add the following code.

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: {
    app: './src/index.js'
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist')
  },
  devServer: {
    contentBase: './dist',
    hot: true
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ]
};

Note a few things have changed since the previous post. We are declaring that the devServer will be looking for the contentBase in the ./dist folder, so move the index.html file from the root directory into ./dist.

Also, we have renamed main.js to bundle.js. “Main” and “Index” are too similar, and “Bundle” is a little more descriptive. Make sure you make the src attribute change in index.html to reflect this.

This file, webpack.config.js is not required in webpack 4 or higher, but it is very useful to customize your development.

Next add the --hot tag to your webpack-dev-server script in the package.json file. See below.

"webpack-dev-server": "webpack-dev-server --hot",

Next run the following commands in your terminal while in your root directory:

npm run webpack
npm run webpack-dev-server

Your folder structure should now look like this.

Try changing something in your Javascript code, and your browser on localhost:8080 should refresh automatically.

1 thought on “Adding Hot Module Replacement (HMR) to Webpack”

Leave a Comment