demo地址: https://github.com/Lkkkkkkg/webpack-demo
继上一次配置完多页面提取公共部分js&css: https://blog.csdn.net/qq593249106/article/details/84937856
使用 RectHotLoader
react 提供了 react-hot-loader 插件来帮助 webpack 配置下 react 实现热替换,
安装
npm i react-hot-loader --save-dev
配置.babelrc
.babelrc
{
"presets": ["env", "react"],
"plugins": ["react-hot-loader/babel"]
}
配置 Webpack.config.js
将 devMode 改为 true, 进行开发模式(防止 css 压缩导致不能进行 css 热替换), 测试热替换:
Webpack.config.js
var devMode = true; //设为开发模式
module.exports = {
module: {
rules: [ //配置加载器, 用来处理源文件, 可以把es6, jsx等转换成js, sass, less等转换成css
{
test: /\.(sa|sc|c)ss$/,
use: [
devMode ? 'style-loader' : MiniCssExtractPlugin.loader, //开发模式下不能用MiniCssExtractPlugin.loader来压缩css,否则热替换报错
'css-loader',
'sass-loader',
],
},
]
}
修改 package.json, 加上 --hot 启动热替换:
package.json:
{
"name": "demo05",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack",
"dev": "webpack-dev-server --open --hot"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^1.0.0",
"css-loader": "^2.0.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.5.0",
"node-sass": "^4.11.0",
"optimize-css-assets-webpack-plugin": "^5.0.1",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-hot-loader": "^4.3.12",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^4.27.1",
"webpack-cli": "^3.1.2",
"webpack-dev-server": "^3.1.10"
},
"dependencies": {
"lodash": "^4.17.11"
}
}
修改 App.js使用热替换:
App.js
import React from 'react'
import { hot } from 'react-hot-loader'
const App = () => (
<h1>
Index Change<br />
</h1>
)
export default hot(module)(App)
运行服务器
终端输入 npm run dev, 弹出网页, 修改 js , 页面没有刷新, 页面的内容自动变化, 控制台出现HMR的字眼:
修改 sass, 页面没有刷新, 同样能完成热替换