【笔记】Webpack的WebServer

前言

Webpack的WebServer,实现重新打包后自动刷新浏览器

下载依赖

1
npm install -D webpack-dev-server

修改配置文件

devServer:WebServer配置

host:指定主机地址
port:指定端口号
open:自动打开浏览器
static:指定打包后的静态资源目录
compress:使用gzip压缩
headers:添加响应头
proxy:配置代理,在使用fetch()发送请求时,自动改为向指定服务器发送请求
http2:启用https
historyApiFallback:如果开启了历史API回调,则当访问的路径不存在时,自动改为访问主页
hot:启用热模块替换,将打包后的文件放到内存中,优先级高于liveReload
liveReload:启用项目热部署,将打包后的文件输出为文件

webpack.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
module.exports = {
devServer: {
host: 0.0.0.0,
port: 8080,
open: true,
static: "./dist",
compress: true,
headers: {
"key": "value",
},
proxy: {
"/api": "http://127.0.0.1:9000/",
},
http2: true
historyApiFallback: true,
hot: true,
liveReload: true,
}
}

HTTPS配置

使用Webpack自签名证书

webpack.config.js
1
2
3
4
5
module.exports = {
devServer: {
https: true
}
}

自定义HTTPS证书

webpack.config.js
1
2
3
4
5
6
7
8
9
10
11
12
module.exports = {
devServer: {
https: {
cacert: "./server.pem",
pfx: "./server.pfx",
key: "./server.key",
cert: "./server.crt",
passphrase: "webpack-dev-server",
requestCert: true,
}
}
}

热模块替换配置(Hot Module Replacement)

修改配置文件

webpack.config.js
1
2
3
4
5
module.exports = {
devServer: {
hot: true
}
}

为指定模块启用热模块替换

  • 如果是CSS模块,则无需手动进行刷新,因为css-loader已经自动进行刷新
  • 如果是JS模块,则需要通过调用accept()函数启用热模块替换
    • 如果是React、Vue等框架,则无需手动进行刷新,因为框架已经进行自动刷新
index.js
1
2
3
if (module.hot) {
module.hot.accept("./file.js");
}
index.js
1
2
3
4
5
if (module.hot) {
module.hot.accept("./file.js", function () {
// 完成热模块替换回调函数
});
}

热部署配置

修改配置文件

webpack.config.js
1
2
3
4
5
module.exports = {
devServer: {
liveReload: true
}
}

启动WebServer

--open:部署WebServer完成后立即自动打开浏览器

1
webpack-dev-server

在执行打包后启动WebServer

1
webpack serve

完成