Hot Module Replacement

In notebook:
FrontEndMasters Webpack Deep Dive
Created at:
JavaScript Webpack libraries React

Hot module replacement

Live reload, but much better

FEM/01.6-hmr branch

The idea is that you don't have to manually refresh the page after having changed the code in one of your sub-modules. Especially frustrating, if you have to reset the UI state each time. 


Webpack wraps webpackHotUpdate around your file. Anywhere your file is required, Webpack passes the webpackHotUpdate wrapper and not directly your file. webpackHotUpdate will send the updates. 

Not very complicated to set up in fact
  // ****   bootstrap.js  ****

/* eslint no-console:0 */
var app = require('./app')
var helpers = require('./helpers')

// this is only relevant when using `hot` mode with webpack
// special thanks to Eric Clemmons:
// detects if hot reload is active
const reloading = document.readyState === 'complete'

// this ( ↓) is the same object that has
// module.exports
// but supercharged by Webpack (monkey-patched)

// if the --hot flag is not present,
// this becomes dead code and is removed
if ( {
  // you can accept one file
  // or accept all files as here ↓ {
    console.log('❌  HMR Error:', err)
  // if accepted, then the file is reloaded
  // in React this is great
  // and while Reduc fits well with this
  // state and view separate
  if (reloading) {
    console.log('πŸ”  HMR Reloading.')
  } else {'βœ…  HMR Enabled.')
} else {'❌  HMR Not Supported.')

function bootstrap() {
  helpers.$on(window, 'load', app.onLoad)
  helpers.$on(window, 'hashchange', app.onLoad)
  // ****   package.json  ****

  "scripts": {
    "prebuild": "rimraf dist",
    "build": "webpack -p",
    "prebuild:dev": "rimraf dist",
    "build:dev": "webpack",
    "start": "http-server",
    // 1. ++++ add the --hot flag
    "dev": "webpack-dev-server --hot",
    "debug": "node-nightly --inspect --debug-brk node_modules/.bin/webpack --env.debug",
Now you can see in the browser console that HMR is enabled. ( β€‹$ npm run dev​ )

Now, you can change any file and it will be hot reloaded in the browser. 

If your doing React, then there's a loader that makes this even easier. It works great with NodeJS and Express (see comment above). 

This only works with the Webpack Dev Server (and the β€‹--hot​ command line flag, or set it in the config)