Azure Pipelines中React .NET项目npx vite build证书创建失败
问题解决:React .NET项目Azure Pipeline中
npx vite build证书生成失败 问题根源
你的报错出在vite配置的证书生成逻辑:不管是本地还是CI环境,代码都会先检查HTTPS证书文件,不存在就调用dotnet dev-certs生成。但Azure Pipeline的Windows虚拟机默认没有预先生成ASP.NET HTTPS开发证书,且CI环境下执行dotnet dev-certs https --export-path会因为权限/环境限制失败,直接中断构建。
更关键的是:你虽然区分了configLocal和configServer,但证书生成代码是在配置导出之前执行的——不管isCI是true还是false,这段代码都会跑,这就是CI环境报错的核心原因。
修复方案
把证书生成逻辑包裹在!isCI条件里,只有本地环境才执行证书检查和生成,CI环境直接跳过:
修改后的vite.config.ts关键部分:
import { fileURLToPath, URL } from "node:url"; import { defineConfig, UserConfig } from "vite"; import plugin from "@vitejs/plugin-react"; import fs from "fs"; import path from "path"; import child_process from "child_process"; import mkcert from "vite-plugin-mkcert"; const isCI = process.env.CI === 'true' || process.env.AZURE_PIPELINE === 'true'; const baseFolder = process.env.APPDATA !== undefined && process.env.APPDATA !== "" ? `${process.env.APPDATA}/ASP.NET/https` : `${process.env.HOME}/.aspnet/https`; //@ts-ignore const certificateArg = process.argv.map((arg) => arg.match(/--name=(?<value>.+)/i)).filter(Boolean)[0]; const certificateName = certificateArg ? certificateArg.groups.value : "name.client"; let certFilePath = ''; let keyFilePath = ''; // 仅本地环境处理证书逻辑 if (!isCI) { if (!certificateName) { console.error("Invalid certificate name. Run this script in the context of an npm/yarn script or pass --name=<<app>> explicitly."); process.exit(-1); } certFilePath = path.join(baseFolder, `${certificateName}.pem`); keyFilePath = path.join(baseFolder, `${certificateName}.key`); if (!fs.existsSync(certFilePath) || !fs.existsSync(keyFilePath)) { if ( 0 !== child_process.spawnSync("dotnet", ["dev-certs", "https", "--export-path", certFilePath, "--format", "Pem", "--no-password"], { stdio: "inherit", }).status ) { throw new Error("Could not create certificate."); } } } const configLocal : UserConfig = { plugins: [plugin(), mkcert()], resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)), }, }, server: { proxy: { "^/weatherforecast": { target: "https://localhost:7293/", secure: false, }, }, port: 5173, https: { key: fs.readFileSync(keyFilePath), cert: fs.readFileSync(certFilePath), }, }, } const configServer : UserConfig = { plugins: [plugin(), mkcert()], resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)), }, }, server: { proxy: { "^/weatherforecast": { target: "https://localhost:7293/", secure: false, }, }, port: 5173, }, } export default defineConfig(isCI ? configServer : configLocal);
补充说明
CI环境下执行vite build生成的是静态产物,和开发服务器的HTTPS配置完全无关,所以完全可以跳过所有证书相关逻辑,避免不必要的环境依赖问题。
另外检查你的流水线配置:当前给出的步骤里没有显式执行npx vite build,如果是在项目post-build事件中触发的前端构建,确保修改后的vite配置能正确识别CI环境变量。
内容的提问来源于stack exchange,提问作者Stanley
相关产品推荐
相关产品推荐

