HMR(Hot Module Replacement)– One of the most useful features webPack provides, it allows various modules to be updated at run time without a full refresh.

How to enable: add a hot parameter to devServer in webpack.config.js — only listen for changes in JS files.

DevServer: {port: 8080, /* Specifies the port */ compress: true, /* Enable automatic compression */ open: true, /* Automatically open the browser */ hot: true /* Enable module hot replacement */}

Listen for changes to the HTML file. Since HTML does not have HMR functionality, you just need to import the HTML file in the entry.

entry: ['./index.js','./index.html']

For style HMR functionality, just use the style-loader in the development environment (replace it with mini-CSs-extract-plugin when packaging).

module: {
    rules: [
        {
            test: /\.css$/,
            use: ['style-loader','css-loader','postcss-loader']    
        }
    ]
}

Js has no HMR function by default, so it can only handle js files that are not entry files. The solution is: After hot is enabled, the module.hot interface is exposed in index.js.

If (module. Hot) {/ * tell webpack accept hot replacement module * / module in hot. Accept (' / [on the path of the js] ', () = > {})}

The server detects a change in js code and executes the module.hot.accept callback

Webpack’s built-in Tree-shaking can automatically remove js code we don’t actually use when packaging, but only if the following conditions are met:

A. Must use es6 modular development B. must use production mode

Use purgecss-webpack-plugin to remove unwanted CSS code. Use mini-css-extract-plugin to install

npm i purgecss-webpack-plugin -D

B. Configure in webpack.config.js

const (resolve,join) = require('path'); /* path.resolve() in node resolves a sequence of paths or fragments into an absolute path, equivalent to the CD operation */ /* path.join() in node links path fragments with a specific separator '/', */ const PATHS = require('glob') /*glob is a global object for node */ const PATHS = {SRC: join(__dirname,'src')} const MiniCssExtractPlugin = require('mini-css-extract-plugin') const PurgecssPlugin = / module.exports = {entry: './ SRC /xxx.js', output: {filename: '[name].js', path: resolve(__dirname, 'dist') }, module: { relus: [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, 'css-loader' ] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: '[name].css' }), new PurgecssPlugin({ paths:glob.sync(`${PATHS.src}/**/*`,{nodir:true}) }) ] }