What is hot substitution?

Hot Module Replacement means that when we build a project using WebPack in development mode, when we change the code in the project file, not only does the Webpack have to be rebuilt, but the browser also has to update the page synchronously. So hot replacement doesn’t reduce build time, it reduces the time it takes for code to change to render.

When using Webpack-dev-server, consider the process of updating the code to render the effects

Graph of TD code changes - > repackaged -- > refresh browser requests all resources -- -- > browser code execution -- - > | | monitoring code changes

With hot substitution, the process changes

Graph of TD code changes - > repackaged -- -- > browser requests only change resources > browser code execution -- > | | monitoring code changes

The main thing HMR does is avoid having to refresh the browser every time you change the code.

Usage and Principle

Change the configuration

    module.exports = {
         devserver: {
            hot: true / / open HMR
        },
        plugins: [
            new webpack.HotModuleReplacementPlugin() / / is optional]}Copy the code

Change the code

    //index.js
    if(module.hot){ // Whether to enable hot update
        module.hot.accept() // Accept hot updates
    }
Copy the code

Note: Where did the above code module come from? We know that the packaged code is run in function(module,exports,_webpack_require_){}, so this module is also provided by that function

When hot updates are enabled, webpack-dev-server injects the module.hot property into the package result. By default, webpack-dev-server does not enable hot updates. Both call location.reload to refresh the page. However, this behavior is changed if modlue.hot.accept() is run. Module.hot.accept () lets the server send updates to the browser.

However, based on the HTTP protocol, the server cannot actively send information to the browser. In this case, we need to use WebSocket, based on WebSocket, so that webpack-dev-server can actively send the latest resources to the browser after the code update.

Graph of TD browser - > | web socket | server - > | web socket | browser

And then the results to the plug-in HotModuleReplacementPlugin injected code execution, plug-in HotModuleReplacementPlugin according to cover the original code, and then let the code to execute.

So hot replacement happens while the code is running

Style hot replacement

For the style, also can use the hot replacement, but you need to use the style – loader, because the time of the hot replacement HotModuleReplacementPlugin will only simply rerun the module code, So the style-loader code resets the style in the style element as soon as it runs. The Mini-CSS-Extrat-plugin, because it generates files during build and cannot change them during run time, is not effective for hot replacement.