背景

在上一节中,已经能够生成一个能够自动重新编译本地服务器了,但是,有一个问题,在项目写的比较大的时候,每次打包的时间就会变得很长,为了解决这个问题,webpack也支持使用模块热替换的方式来进行差异修改,也就是热更新,可以在每次修改的时候,只重新刷新修改的那一部分,这样刷新的速度就会变得很快了。

方案

webpack为这种情况,提供了插件

  1. HotModuleReplacementPlugin启用热模块更换,也称为HMR
  2. NamedModulesPlugin该插件会显示模块的相对路径

写法

修改config.webpack.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    //config.webpack.js
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
+ const webpack = require('webpack');
module.exports = {
//配置函数接受两个参数env和argv
//env:环境对象
//Webpack-CLI 的命令行选项
entry: './src/index.js', //设置默认
output: {
...,
},
devtool: 'inline-source-map',
module: {
...,
},
devServer: {
contentBase: './dist',
+ hot: true
},
plugins: [
new CopyWebpackPlugin([
{
from: path.join(__dirname, '/staticFrom/'),
to: path.join(__dirname+'/dist/')
}
]),
+ new webpack.NamedModulesPlugin(),
+ new webpack.HotModuleReplacementPlugin()
]
}

然后修改package.json中的script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
    //package.json
{
"dependencies": {
"babel-loader": "^8.0.6",
"copy-webpack-plugin": "^5.1.1",
"webpack": "^4.41.5",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.10.1"
},
"name": "webpack_learn",
"version": "1.0.0",
"main": "index.js",
"devDependencies": {
"@babel/core": "^7.7.7",
"@babel/preset-env": "^7.7.7",
"babel-core": "^6.26.3",
"babel-preset-env": "^1.7.0"
},
"scripts": {
"build": "webpack",
"watch": "webpack --watch",
- "serve": "webpack-dev-server --open",
+ "serve": "webpack-dev-server --hotOnly",
"dev": "webpack --mode development",
"product": "webpack --mode production",
"testParams": "webpack --mode production --env.production product --param1 1 --param2 2 --explane 这是一个说明",
"showColorAndProgress": "webpack --progress --colors",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": ""
}

然后在命令行中执行

1
npm run serve #也可以yarn watch

此时,就是模块热更新的开发状态啦