浅析webpack热更新

HMR(Hot Module Replacement)定义

HMR会在应用程序运行过程中替换、添加或删除模块,不用重新加载整个页面,这与“自动刷新”不同,webpack-dev-server中的inline控制页面的自动刷新,即当有内容更新时,无需用户手动刷新浏览器。

实现HMR

  • 在webpack配置文件中添加HMR插件
  • webpack的dev server中添加hot参数

但配置完这两步还是不够,还需在JS模块中执行一个webpack提供的API,在React中,可以用react-hot-loader和babel来实现。

这边以一个示例来展开说明。

webpack.config.js:

const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require('webpack'); 
const path = require('path')

module.exports = {
    devServer: {
        contentBase: path.resolve(__dirname, 'build'),
        clientLogLevel: 'warning',
        historyApiFallback: true,
        hot: true, // 热加载
        inline: true,  // 实时刷新
    },
    module: {
        rules: [
            {
                test: /\.js|jsx$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /\.html$/,
                use: [
                    {
                        loader: "html-loader",
                        options: { minimize: true }
                    }
                ]
            },
            {
                test: /\.css$/,
                use: [MiniCssExtractPlugin.loader, "css-loader"]
            }
        ]
    },
    plugins: [
        new HtmlWebPackPlugin({
            template: "./src/index.html",
            filename: "./index.html"
        }),
        new MiniCssExtractPlugin({
            filename: "[name].css",
            chunkFilename: "[id].css"
        }),
        new webpack.HotModuleReplacementPlugin()//热加载插件
    ]
};

.babelrc:

{
  "presets": [
    "@babel/preset-env",
    "@babel/preset-react"
  ],
  "plugins": [ "react-hot-loader/babel" ]
}

js文件:

import React from "react";
import ReactDOM from "react-dom";
import { hot } from 'react-hot-loader/root'

const App = () => {
    return (
        <div>
            <p>pig1994 and pig1995  </p>
        </div>
    );
};
export default hot(App);
ReactDOM.render(<App/>, document.getElementById("app"));

通过以上配置即可实现React的HMR。
本文代码完整链接:https://github.com/sunshinelover/webpack-sample-project/tree/master

你可能感兴趣的:(前端杂记)