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