Hot module replacement concept: Hot module replacement is only used in the development phase. It is used at run time. Module changes are only partially refreshed, not the whole page

Js module replacement

index.js:

import _ from 'lodash'; import printMe from './print.js'; function component() { const element = document.createElement('div'); const btn = document.createElement('button'); element.innerHTML = _.join(['Hello', 'webpack'], ' '); btn.innerHTML = 'Click me and check the console! '; btn.onclick = printMe; element.appendChild(btn); return element; } document.body.appendChild(component()); if (module.hot) { module.hot.accept('./print.js', function () { console.log('Accepting the updated printMe module! '); printMe(); }); }Copy the code

print.js:

export default function printMe() {
    console.log('printMe before');
}

Copy the code

Enable hot modules in webpack.config.js:

devServer: {
        contentBase: './dist',
        hot: true
    }
Copy the code

Then start WebPack and click the on-screen button to see the following print on the console:

Then modify the printMe function’s output:

export default function printMe() {
    console.log('printMe after');
}
Copy the code

The console outputs the code to start the hot module:

Continue clicking the on-screen button and the console prints the same printMe function:

It after the thermal module was not to refresh the page, the thermal module after the update, the console still retains heat module updates before print out the data: but there is a problem, the thermal module after the update, button trigger is still at the original printMe function, modification method is as follows: index. The replacement js code changes are as follows:

let element = component(); document.body.appendChild(element); if (module.hot) { module.hot.accept('./print.js', function () { console.log('Accepting the updated printMe module! '); document.body.removeChild(element); element = component(); document.body.appendChild(element); }); }Copy the code

CSS Module Replacement

You only need style-loader and CSS-loader to replace the CSS hot module. Style. CSS:

body {
  background: blue;
}
Copy the code

Configure loader in webpack.config.js:

 rules: [
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader']
            }
        ]
Copy the code

Modify the STYLES in THE CSS, you can also see that the screen is not refreshed.