A thermal load
Thermal load is enabled in webpack-dev-server, we default webpack-dev-server in the case of a global refresh the page, you can modify your modules is enabled to make a replacement heat load, do not refresh the page.
Second, the need to do configuration
1. webpack.config.js in (put only need to change the configuration)
(1) devServer configuration
devServer:{
hotOnly:false, //只允许热模块更新 但是启用后浏览器无法自动刷新
hot: true, // 启用热模块
port:3000, //默认端口号
open:true, // 是否自动打开浏览器
},
The above configuration is only recommended hot: true you can not set hotOnly
(2) plugins configuration
`const webpack=require('webpack');`` //记得开头引入
.......我是其他代码
plugins:[
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html',
}),
],
Use webpack.HotModuleReplacementPlugin
remember webpack here at the beginning of the introduction of webpack.config.js
2. Installation of the bays
npm install React-Hot-Loader --save-dev // 需要在react中使用即需要此插件
额外注意:React-Hot-Loader: react-Hot-dom patch is not detected. React 16.6+ features may not work
3. modify react in
(1) in the entry file index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App'
ReactDOM.render( <App />, document.getElementById('app'));
if (module.hot){
module.hot.accept(function (res) {
console.log("执行了")
res()
})
}
module.hot here is to tell webpack to accept the updated module, but even if not by individual test this module can also be achieved hot update react, and here I have no specific reason to find on the Internet
Under (2) App.js file
import React, { Component ,Suspense, lazy} from "react";
import {hot} from 'react-hot-loader' //这里是我们刚刚安装的hot
class App extends Component {
constructor(props) {
super(props)
}
render() {
return ( <div><p>要加油好好学习啊</p></div>);
}
}
export default hot(module)(App); //hot的使用
(3) possible error: Maximum call stack size exceeded
The reason: the use of -hot in package.json in the script and called in question HotModuleReplacementPlugin led to repeated calls in webpack.config.js in
Solution: Remove the package.json in the script to the -hot
Reference link: https: //juejin.im/post/5b363b576fb9a00e6f660f45