如何让Webpack Dev Server同时支持HTTP与HTTPS访问?
解决方案
要让Webpack Dev Server同时支持HTTP和HTTPS访问,由于同一个端口无法同时绑定两种协议,我们需要配置服务分别监听两个不同端口,提供HTTP和HTTPS服务。以下是两种可行的配置方式:
方式一:用concurrently同时启动两个服务实例
- 首先安装依赖包
concurrently,用于并行执行多个命令:
npm install concurrently --save-dev
- 修改
package.json的scripts配置,添加分别启动HTTP、HTTPS服务的命令,以及并行启动的命令:
"scripts": { "dev:http": "webpack server --config ./src/client/webpack.dev.js --no-server-https", "dev:https": "webpack server --config ./src/client/webpack.dev.js", "dev": "concurrently \"npm run dev:http\" \"npm run dev:https\"" }
- 调整
webpack.dev.js,让它根据命令行参数切换端口和HTTPS配置:
const fs = require("fs"); const { merge } = require("webpack-merge"); const common = require("./webpack.common.js"); const path = require("path"); const argv = require('yargs').argv; module.exports = merge(common, { mode: "development", devtool: "eval-source-map", devServer: { static: { directory: path.join(__dirname, "../../dist/client"), }, ...(argv.serverHttps !== false ? { https: { key: fs.readFileSync(path.join(__dirname, "../../keys/key.pem")), cert: fs.readFileSync(path.join(__dirname, "../../keys/cert.pem")), }, port: 8443 } : { port: 8080 }), hot: true, }, });
配置完成后,执行npm run dev,即可同时通过http://localhost:8080(HTTP)和https://localhost:8443(HTTPS)访问服务。
方式二:利用Webpack Dev Server v4的多协议配置
如果你的webpack-dev-server是v4及以上版本,可以直接通过配置server选项同时启动HTTP和HTTPS服务:
修改webpack.dev.js:
const fs = require("fs"); const { merge } = require("webpack-merge"); const common = require("./webpack.common.js"); const path = require("path"); module.exports = merge(common, { mode: "development", devtool: "eval-source-map", devServer: { static: { directory: path.join(__dirname, "../../dist/client"), }, server: { http: true, // 启用HTTP服务 https: { key: fs.readFileSync(path.join(__dirname, "../../keys/key.pem")), cert: fs.readFileSync(path.join(__dirname, "../../keys/cert.pem")), }, }, ports: { http: 8080, // HTTP服务端口 https: 8443, // HTTPS服务端口 }, hot: true, }, });
执行npm run dev后,就能分别通过两个端口访问HTTP和HTTPS服务。
内容的提问来源于stack exchange,提问作者Pravin Poudel
相关产品推荐
相关产品推荐

