• Webpack’s Hot Module Replacement Feature Explained
  • Nathan Sebhastian
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: Hoarfroster
  • Proofreader: 5Reasons, NIA3Y

When developing JavaScript applications, every time we save code changes, we need to reload the browser to refresh the user interface.

Developer tools such as Webpack can listen for changes to project files by monitoring patterns. Once changes are detected, Webpack automatically rebuilds the application and reloads the browser.

But soon developers began to wonder if there was a way to save and update changes to a page without reloading the browser. After all, reloading means losing the state of any execution on the UI:

  • Any modal boxes or dialogs we are using will disappear. We need to start from scratch and repeat the steps to make them appear again.
  • The state of our application will be reset. If we were using a library like React or Vue, we would need to re-perform state changes or persist the state through local storage.
  • To persist the state to local storage, we need to write some extra code. Unless we have this requirement in production, it is very inconvenient to add and remove code for debugging every time we develop.
  • Even minor changes to the CSS code can trigger a browser refresh.

Hot Module Replacement (HMR) is designed to solve this problem, and has become a powerful assistant to speed up front-end development.

How does the HMR function work?

HMR allows us to swap, add, or remove JavaScript modules while the application is running without having to reload the browser. In Webpack this is done by creating an HMR server in the Webpack development server (webpack-dev-server), which communicates with the HMR runtime in the browser via Websocket.

The switch module process is as follows:

  • When you first build your application, Webpack generates a manifest file containing the compiled hashes and a list of all the modules. Webpack willHMR runtimeInjection into the generatedbundle.jsFile.
  • Webpack detects changes to a file as it is saved.
  • The Webpack compiler builds our application with the changes we make, creating a new manifest file and comparing it to the old one. This process is also known as “hot update”.
  • Hot update data is sent to the HMR server, which in turn sends updates to the HMR runtime.
  • The HMR runtime unpacks the hot update data and processes the changes using the appropriate loaders. If we have CSS changes, csS-loader or style-loader will be called. If we make changes to our JavaScript code, babel-loader is usually called.

By enabling the HMR feature, we can let the browser download the new package and unpack the changes without refreshing the browser. The HMR runtime will accept an incoming request from the HMR server containing manifest files and code blocks to replace the current file in the browser.

When saving code changes while running an HMR-enabled application, we can actually see the hot update file sent from the HMR server on the “Network” TAB:

When a “hot update” fails to replace code in the browser, the HMR runtime notifies Webpack-dev-server. Webpack-dev-server will then refresh the browser to download the new bundle.js file. We can disable this behavior by adding hotOnly: True to the Webpack configuration.

How to enable the HMR function

To enable HMR in our project, we need to let our application know how to handle hot updates. We can do this by instantiating the Module. hot API exposed by Webpack:

First, we need to add hot: True to the Webpack configuration file to enable HMR, as shown below:

// webpack.config.js

module.exports = {
    entry: {
        app: './src/index.js',},devtool: 'inline-source-map'.devServer: {
        hot: true./ /... Ignore other configurations
    },
    plugins: [
        // Start the plugin
        new webpack.HotModuleReplacementPlugin(),
    ],
}
Copy the code

After that, we must use the Module.hot API to process incoming HMR requests. This is an example of a common JS project implementation:

// index.js

import component from "./component";

document.body.appendChild(component);

// Check whether the HMR interface is supported
if (module.hot) {
    // Support hot updates
    module.hot.accept();
}
Copy the code

Once Webpack is told we support HMR, the HMR runtime and loader take over to handle the updates.

However, implementing HMR for complex applications can be tricky because we may encounter unwanted side effects, such as event handlers that are still bound to older functions, especially if you use libraries like React or Vue. In addition, we need to ensure that HMR is enabled only in development.

But before we try to implement HMR ourselves, we recommend that you look for a solution that works for our project, as HMR is already integrated into many popular JavaScript application generators.

Create React App and Next. Js have React Fast Refresh built-in, react-specific hot overload implementation. The HMR of Vue CLI 3 is implemented by vue-loader. Svelte and Angular also have their own HMR integrations, so there is no need to write integrations from scratch.

summary

Hot module replacement allows us to see the effect of code changes in the browser without refreshing the browser, thus preserving the state of the front-end application.

But implementing HMR can be tricky because of its side effects. Fortunately, HMR has been implemented in many JavaScript application generators. So we can enjoy this feature directly without having to implement it ourselves.

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.