You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Webpack Dev Server同时支持HTTP与HTTPS访问?

解决方案

要让Webpack Dev Server同时支持HTTP和HTTPS访问,由于同一个端口无法同时绑定两种协议,我们需要配置服务分别监听两个不同端口,提供HTTP和HTTPS服务。以下是两种可行的配置方式:

方式一:用concurrently同时启动两个服务实例

  1. 首先安装依赖包concurrently,用于并行执行多个命令:
npm install concurrently --save-dev
  1. 修改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\""
}
  1. 调整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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 13:39:40