Skip to content

webpack HMR

ythy edited this page Oct 20, 2017 · 1 revision

HMR (Hot Module Replacement)

Hot Module Replacement (or HMR) is one of the most useful features offered by webpack. It allows all kinds of modules to be updated at runtime without the need for a full refresh.
You can use it in development as a replacement for LiveReload. Actually the webpack-dev-server supports a hot mode which tries to update with HMR before trying to reload the whole page.

Enabling HMR

devServer: {
+     hot: true
},

+     new Webpack.NamedModulesPlugin(),
+     new webpack.HotModuleReplacementPlugin()

in .js

if (module.hot) {
  module.hot.accept()
}

NamedModulesPlugin to make it easier to see which dependencies are being patched. (in browser console)

What is needed to use it

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. For example, a router or a subview would be a good place.
If you only want to use it with the webpack-dev-server, just add webpack/hot/dev-server as entry point. Else you need some HMR management code that calls check and apply.

What makes it so cool

  • It’s like LiveReload but for every module, so to speak.
  • You can use it in production.
  • The updates respect your Code Splitting and only download updates for the changed parts of your app.
  • You can use it for parts of your application and it doesn’t affect other modules.
  • If HMR is disabled all HMR code is removed by the compiler (wrap it in if(module.hot))
Clone this wiki locally