Hot Module Replacement
#
Hot Module Replacement (HMR) builds on top of the WDS. It enables an interface that makes it possible to swap modules live. For example, style-loader can update your CSS without forcing a refresh. Implementing HMR for styles is ideal because CSS is stateless by design.
HMR is possible with JavaScript too, but due to application state, it’s harder. react-refresh-webpack-plugin↗ and vue-hot-reload-api↗ are good examples.
localStorage
and then hydrate the application based on that after a refresh. Doing this pushes the problem to the application side.
Enabling HMR
#
The following steps need to be enabled for HMR to work:
- The development server has to run in the hot mode to expose the hot module replacement interface to the client.
- Webpack has to provide hot updates to the server and can be achieved using
webpack.HotModuleReplacementPlugin
. - The client has to run specific scripts provided by the development server. They will be injected automatically but can be enabled explicitly through entry configuration.
- The client has to implement the HMR interface through
module.hot.accept
and optionallymodule.hot.dispose
to clean module before replacing it.
Using webpack-dev-server --hot
or running webpack-plugin-serve in hot
mode solves the first two problems. In this case, you have to handle only the last one yourself if you want to patch JavaScript application code. Skipping the --hot
flag and going through webpack configuration gives more flexibility.
The following listing contains the essential parts related to this approach. You will have to adapt from here to match your configuration style:
{
devServer: {
// Don't refresh if hot loading fails. Good while
// implementing the client interface.
hotOnly: true,
// If you want to refresh on errors too, set
// hot: true,
},
plugins: [
// Enable the plugin to let webpack communicate changes
// to WDS. --hot sets this automatically!
new webpack.HotModuleReplacementPlugin(),
],
}
module.hot
. import.meta.webpackHot
has been designed with ES2015 modules and Node mjs file extension in mind as it doesn’t allow mixing CommonJS and ES2015 syntax.
If you implement configuration like above without implementing the client interface, you will most likely end up with an error:
The message tells that even though the HMR interface notified the client portion of the code of a hot update, nothing was done about it and this is something to fix next.
optimization.moduleIds = 'named'
. If you run webpack in development
mode, it will be on by default.
Implementing the HMR interface
#
Webpack exposes the HMR interface through a global variable: module.hot
. It provides updates through module.hot.accept(<path to watch>, <handler>)
function and you need to patch the application there.
The following implementation illustrates the idea against the tutorial application:
src/index.js
import component from "./component";
let demoComponent = component();
document.body.appendChild(demoComponent);
// HMR interface
if (module.hot) {
// Capture hot update
module.hot.accept("./component", () => {
const nextComponent = component();
// Replace old content with the hot loaded one
document.body.replaceChild(nextComponent, demoComponent);
demoComponent = nextComponent;
});
}
If you refresh the browser, try to modify src/component.js
after this change, and alter the text to something else, you should notice that the browser does not refresh at all. Instead, it should replace the DOM node while retaining the rest of the application as is.
module.hot.accept
works with an array of filenames as well. The handler (second parameter) is optional.
The image below shows possible output:
The idea is the same with styling, React, Redux, and other technologies. Sometimes you don’t have to implement the interface yourself even as available tooling takes care of that for you.
module.hot.accept
code has to evolve to capture changes to it as well.
if(module.hot)
block is eliminated entirely from the production build as minifier picks it up. The Minifying chapter delves deeper into this topic.
if (module.hot) { module.hot.accept(); }
for each module that was matched. It’s useful in case you have modules that should accept hot loading without implementing the patching behavior.
Setting WDS entry points manually
#
In the setup above, the WDS-related entries were injected automatically. Assuming you are using WDS through Node, you would have to set them yourself as the Node API doesn’t support injecting. The example below illustrates how to achieve this:
entry: {
hmr: [
// Include the client code. Note host/post.
"webpack-dev-server/client?http://localhost:8080",
// Hot reload only when compiled successfully
"webpack/hot/only-dev-server",
// Alternative with refresh on failure
// "webpack/hot/dev-server",
],
...
},
HMR and dynamic loading
#
Dynamic Loading through require.context
and HMR requires extra effort:
const req = require.context("./pages", true, /^(.*\.(jsx$))[^.]*$/g);
module.hot.accept(req.id, ...); // Replace modules here as above
Conclusion
#
HMR is one of those aspects of webpack that makes it attractive for developers and webpack has taken its implementation far. To work, HMR requires both client and server-side support. For this purpose, webpack-dev-server provides both. You will have to take care with the client-side, though, and either find a solution that implements the HMR interface or implement it yourself.