webpack配置devServer配置https代理与证书
Author:zhoulujun Date:
Webpack-dev-server 配置https
浏览器如果需要开发某些特定功能,需要https浏览器才会给予功能权限, 则开发时我们需要在https环境
//webpack.config.js
module.exports = {
//...
devServer: {
port: 8080,
proxy: [{
context: ['/api'], //将 "https://urlname.com:8080/api" 转发到 "https://127.0.0.1:6495/api"
target: 'https://127.0.0.1:6495',
secure: false,
changeOrigin: true
}],
host: '0.0.0.0',
allowedHosts: [ 'urlname.com' ],
https: { //开启的端口可以通过https访问
key: fs.readFileSync('./cert/urlname.com.key'),
cert: fs.readFileSync('./ecrt/urlname.crt')
}
}
}
Webpack-dev-server的proxy http 转https
dev-server 使用了非常强大的 http-proxy-middleware , http-proxy-middleware 基于 http-proxy 实现的,可以查看 http-proxy 的源码和文档:https://github.com/nodejitsu/node-http-proxy 。
基本配置:
webpackConfig.devServer = {
host: 'local.zhoulujun.net',
port: 3004,
proxy: {
'/api/': {
target: 'http://local.zhoulujun.net:3000/',
logLevel: 'debug',
pathRewrite:{
'^/api':'/api'
},
ws: false,
secure: false,
changeOrigin: true,
},
'/upload/': {
target: 'http://local.zhoulujun.net:3000/',
ws: false,
changeOrigin: true,
secure: false
},
},
overlay: {
warnings: true,
errors: true,
},
quiet: false,
};
proxy 参数解析:
target:接口的域名
changeOrigin:本地就会虚拟一个服务器接收你的请求并代你发送该请求, 如果接口跨域,需要进行这个参数配置
secure:默认情况下,不接受运行在 HTTPS 上,且使用了无效证书的后端服务器。如果你想要接受,需要设置 secure: false 就行
pathRewrite: pathRewrite 来重写地址,例如将前缀 '/api' 转为 '/web'
ws:true / false,是否代理websockets
xfwd:true / false,添加x-forward标
agent:要传递给http(s).request的对象(请参阅Node的https代理和http代理对象)
bypass:有时你不想代理所有的请求。可以基于一个函数的返回值绕过代理。在函数中你可以访问请求体、响应体和代理选项。必须返回 false 或路径,来跳过代理请求。
例如:对于浏览器请求,你想要提供一个 HTML 页面,但是对于 API 请求则保持代理。你可以这样做:
module.exports = {
//...
devServer: {
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';
}
}
}
}
}
};
externals和libraryTarget的关系
libraryTarget配置如何暴露 library。如果不设置library,那这个library就不暴露。就相当于一个自执行函数
externals是决定的是以哪种模式去加载所引入的额外的包
libraryTarget决定了你的library运行在哪个环境,哪个环境也就决定了你哪种模式去加载所引入的额外的包。也就是说,externals应该和libraryTarget保持一致。library运行在浏览器中的,你设置externals的模式为commonjs,那代码肯定就运行不了了。
如果是应用程序开发,一般是运行在浏览器环境libraryTarget可以不设置,externals默认的模式是global,也就是以全局变量的模式加载所引入外部的库。
参考文章:
webpack配置devServer配置https代理与证书 https://blog.csdn.net/qq_41614928/article/details/112758616
Webpack-dev-server的proxy用法 #42 https://github.com/funnycoderstar/blog/issues/42
webpack externals 深入理解 https://segmentfault.com/a/1190000012113011
转载本站文章《webpack配置devServer配置https代理与证书》,
请注明出处:https://www.zhoulujun.cn/html/tools/Bundler/webpack/2022_0515_8817.html