读取动态配置

This commit is contained in:
chenxing
2026-09-01 11:50:38 +08:00
parent 886cce1b9e
commit 428ee56bd3
2 changed files with 42 additions and 2 deletions
+22
View File
@@ -5,6 +5,28 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="../../favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- 运行时配置引导:在任何应用模块执行前同步拉取 /<应用>/<前端目标>/api/env-config
(projman 配置管理在线维护、双写 Nacos),替代 config/index.js 与构建期 VITE_* 环境变量。
必须同步:host.config.ts 在模块求值期就读 window.__APP_CONFIG__;失败/本地开发
(路径不足两段)则不设置,应用自动走 import.meta.env 构建期兜底,页面加载不受影响。
注意:同步 XHR 不支持 timeout 属性(赋值会抛 InvalidAccessError),依赖内网快速失败 -->
<script>
(function () {
try {
var seg = location.pathname.split("/").filter(Boolean);
if (seg.length < 2) return; // 本地开发(根路径):无应用上下文,走构建期配置
var xhr = new XMLHttpRequest();
xhr.open("GET", "/" + seg[0] + "/api/env-config?front=" + encodeURIComponent(seg[1]), false);
xhr.send(null);
if (xhr.status === 200) {
var conf = JSON.parse(xhr.responseText);
if (conf && typeof conf === "object") window.__APP_CONFIG__ = conf;
}
} catch (e) {
/* 拉取失败保持未设置,走构建期兜底 */
}
})();
</script>
<title><%- title %></title>
<link rel="stylesheet" href="./libs/ztree/zTreeStyle.css" />
<script src="./libs/jquery.min.js"></script>
+20 -2
View File
@@ -1,8 +1,10 @@
import { BaseConf } from "@/types/Basics";
/**
* 通过 Vite 环境变量管理配置,不再依赖 window.conf / config.js
* 环境变量定义在项目根目录的 .env.dev / .env.base / .env.ld 中
* 配置优先级(高 → 低):
* ① window.__APP_CONFIG__:运行时配置,index.html 引导脚本在应用模块加载前同步拉取
* /<应用>/<前端目标>/api/env-config(projman 配置管理在线维护、双写 Nacos)写入
* ② Vite 环境变量(构建期,定义在 .env.dev / .env.base / .env.ld 中):接口拉取失败/本地开发时兜底
*/
const env = import.meta.env;
@@ -18,6 +20,22 @@ let conf: BaseConf = {
isDebug: env.DEV,
};
// 运行时配置覆盖:只覆盖运行时配置里实际出现的键(含 relayConf 逐键合并),未配置的键沿用构建期值
const runtime = (window as any).__APP_CONFIG__;
if (runtime && typeof runtime === "object") {
const { relayConf, ...flat } = runtime;
Object.keys(flat).forEach(key => {
if (flat[key] !== undefined && flat[key] !== null && flat[key] !== "") {
(conf as any)[key] = flat[key];
}
});
if (relayConf && typeof relayConf === "object") {
Object.keys(relayConf).forEach(key => {
if (relayConf[key]) (conf.relayConf as any)[key] = relayConf[key];
});
}
}
// HTTPS 自动升级:当前页面是 https 时,将所有 http:// 配置项升级为 https://
var ishttps = "https:" == document.location.protocol ? true : false;
if (ishttps) {