webpack devServer开发服务常用配置
- 前端
- 三生万物
- 0
一、publicPath公共路径
publicPath路径下的打包文件可在浏览器中访问。
默认:/
,通过http://localhost:8080/bundle.js
访问
指定目录访问
publicPath: "/assets/"
通过http://localhost:8080/assets/bundle.js
访问
devServer.publicPath 和 output.publicPath 一样被推荐。
二、proxy代理配置
由于前端不能直接调用后端接口,存在跨域,所以需要代理配置,webpack使用的是 http-proxy-middleware 中间件处理的。
1、简单示例:
proxy: {
"/api": "http://localhost:3000"
}
请求 /api/user
会被代理到 http://localhost:3000/api/user
。
2、路径重写
proxy: {
"/api": {
target: "http://localhost:3000",
pathRewrite: {"^/api" : ""}
}
}
请求 /api/user
会被代理到 http://localhost:3000/user
。
3、多个特定路径
如果你想代理多个特定的路径到同一个目标,可以配置context
路径数组实现
proxy: [{
context: ["/auth", "/api"],
target: "http://localhost:3000",
}]
请求 /auth/user
和 /api/user
会被代理到 http://localhost:3000/user
4、允许不安全https访问
proxy: {
"/api": {
target: "https://other-server.example.com",
secure: false
}
}
5、绕过代理
匹配到html则跳过代理直接返回
proxy: {
"/api": {
target: "http://localhost:3000",
bypass: function(req, res, proxyOptions) {
if (req.headers.accept.indexOf("html") !== -1) {
// console.log("Skipping proxy for browser request.");
return "/index.html";
}
}
}
}
三、open
启动服务后自动打开浏览器
devServer: {
open: true
}
四、修改端口号
devServer: {
port: 3001
}
五、quiet静默模式
devServer: {
quiet: true
}
开启后,除了初始启动信息之外的任何内容都不会被打印到控制台
六、socket
devServer: {
socket: 'socket'
}
七、白名单管理
devServer: {
allowedHosts: [
'host.com',
'subdomain.host.com',
'subdomain2.host.com',
'host2.com'
]
}
八、https
默认情况下,dev-server 通过 HTTP 提供服务。也可以选择带有 HTTPS 的 HTTP/2 提供服务
devServer: {
https: true
}
指定证书
devServer: {
https: {
key: fs.readFileSync("/path/to/server.key"),
cert: fs.readFileSync("/path/to/server.crt"),
ca: fs.readFileSync("/path/to/ca.pem"),
}
}
九、自定义响应头
在所有响应中添加headers
内容
devServer: {
headers: {
"X-Custom-Foo": "bar"
}
}
十、压缩
devServer: {
compress: true
}
一切服务都启用gzip压缩
十一、日志
devServer: {
clientLogLevel: "none"
}
值有:
- none 关闭所有日志
- error 只显示错误日志
- warning 只显示告警日志
- info 只显示信息日志
除了这个,还可以直接设置noInfo控制
devServer: {
noInfo: true // 只显示错误和告警
}
十二、惰性模式
不监听文件变动
devServer: {
lazy: true
}
十三、host
默认是localhost
,如果你想其他电脑也可以访问,可以设置如下:
devServer: {
host: "0.0.0.0"
}
十四、contentBase
默认情况下,将使用当前工作目录作为提供内容的目录, 可以修改为其他目录
devServer: {
contentBase: path.join(__dirname, "public")
}
推荐使用绝对路径
可以提供多个目录
devServer: {
contentBase: [path.join(__dirname, "public"), path.join(__dirname, "assets")]
}
禁止
devServer: {
contentBase: false
}
- output的publicPath是用来给生成的静态资源路径添加前缀的
- devServer中的publicPath是用来本地服务拦截带publicPath开头的请求的
- contentBase是用来指定被访问html页面所在目录的
参考链接:
- https://blog.csdn.net/wang839305939/article/details/85855967
免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。