Concept: Hot Module Replacement, or HMR for short. You can configure it to avoid frequently refreshing the browser page manually, but instead of refreshing the entire page, you can partially replace some of the module code and make it work, and you can see the effect of the code changes. Therefore, HMR can not only avoid frequent manual page refresh, but also reduce the wait for page refresh, which can greatly improve the efficiency of front-end page development.

Out of the box

Note: Configure devServer in webpack.config.js to use

  • 1. Inwebpack.config.jsIn the configuration
. Module. exports = {mode: 'development', // specify buildmode... DevServer: {hot: true, open: true, // Start serve automatically open page port: 8080, // port number}}Copy the code
  • 2. We use cases in code

Note: Delete the previous section code and add CSS-loader to webpack.config.js. Item SRC directory to add, keep the index.html index.js style. CSS file a.webpack.config.js configuration read CSS file

. module.exports = { ... Module: {rules: [... {test: / \. CSS $/, / /. Use CSS file configuration: [' style - loader ', 'CSS - loader]}]}, devServer: {hot: True, open: true, port: 8080, // hotOnly: true, // proxy: {// configure proxy // '/ API ': 'http://localhost:3000' //}}}Copy the code

B. Create the content in SRC /index.js

import './style.css' var btn = document.createElement('button'); Btn. innerHTML = 'new '; document.body.appendChild(btn); btn.onclick = function() { var div = document.createElement('div'); div.innerHTML = 'item'; document.body.appendChild(div); }Copy the code

C. Add a style in SRC /style. CSS

div:nth-of-type(odd) {
    background: red;
}
Copy the code

D. Effect display of startup projectNote: after clicking “Add” button, the content with red background will appear.

E. Next we modify the background style in SRC /style. CSS

div:nth-of-type(odd) {
    background: green;
}
Copy the code

Note: at this time we did not do any refresh, the page will automatically give me a new piece of content.

As shown in the figure below

  • 3..jsHot module update of code

Note: write CSS styles can already be generated, no problem, this time we need to modify the JS code is the same. PS: To be continued…