feat: 区分开发和生产环境配置并完善加载与回归测试

This commit is contained in:
zhanjunhao
2026-10-27 15:55:20 +08:00
parent 7b9cc0ba40
commit 3ffba4ac6c
9 changed files with 271 additions and 113 deletions
+12
View File
@@ -0,0 +1,12 @@
# Loaded by npm run dev. Override locally in .env.development.local.
# Public configuration only; VITE_* values are exposed to the browser.
VITE_REACT_APP_SERVER_URL=
VITE_CLOUD_BRAIN_UI_ENABLED=false
# Vite development proxy only. Keep the browser URL empty to use this proxy.
DEV_PROXY_TARGET=http://134.175.227.134:13000
# Optional analytics. Empty IDs disable script injection.
VITE_UMAMI_WEBSITE_ID=
VITE_UMAMI_SCRIPT_URL=https://analytics.umami.is/script.js
VITE_GOOGLE_ANALYTICS_ID=
-8
View File
@@ -1,8 +0,0 @@
# Backend root URL. Leave empty for same-origin requests (Vite proxy in development).
# Restart the dev server or rebuild production assets after changing this value.
# Public configuration only; never put secrets in VITE_* variables.
VITE_REACT_APP_SERVER_URL=
# Frontend build-time feature flags. Rebuild the frontend after changing them.
# Missing or false keeps the Cloud Brain suite hidden and blocks direct routes.
VITE_CLOUD_BRAIN_UI_ENABLED=false
+11
View File
@@ -0,0 +1,11 @@
# Loaded by npm run build. Override locally in .env.production.local or in CI.
# Public configuration only; VITE_* values are exposed to the browser.
# Empty URL uses same-origin requests; configure your production reverse proxy.
# Set a backend root URL for cross-origin requests, then rebuild and redeploy.
VITE_REACT_APP_SERVER_URL=
VITE_CLOUD_BRAIN_UI_ENABLED=false
# Optional analytics. Empty IDs disable script injection.
VITE_UMAMI_WEBSITE_ID=
VITE_UMAMI_SCRIPT_URL=https://analytics.umami.is/script.js
VITE_GOOGLE_ANALYTICS_ID=
+3 -3
View File
@@ -44,8 +44,8 @@ Thumbs.db
Desktop.ini Desktop.ini
.env .env
.env.* .env.*
!.env.example !.env.development
!.env.*.example !.env.production
.env.local .env.local
.env.development.local .env.development.local
.env.test.local .env.test.local
@@ -58,4 +58,4 @@ yarn-error.log*
yarn.lock yarn.lock
# i18n 批次中间产物(可由 scripts/i18n_kt_batches.cjs 重新生成,勿入库) # i18n 批次中间产物(可由 scripts/i18n_kt_batches.cjs 重新生成,勿入库)
scripts/kt_batches/ scripts/kt_batches/
scripts/kt_out/ scripts/kt_out/
+13 -13
View File
@@ -45,17 +45,17 @@ npm run dev
默认访问 <http://localhost:5173>,端口被占用时以终端实际输出为准。开发服务监听 `0.0.0.0`。开发代理目标由 `DEV_PROXY_TARGET` 指定,具体代理配置见下一节。 默认访问 <http://localhost:5173>,端口被占用时以终端实际输出为准。开发服务监听 `0.0.0.0`。开发代理目标由 `DEV_PROXY_TARGET` 指定,具体代理配置见下一节。
需要调整功能开关时,将 `.env.example` 复制为 `.env.local`: 项目已提供两个自动加载的环境配置,无需复制示例文件:
```bash | 命令 | 默认模式 | 配置文件 |
# Git Bash / macOS / Linux | --- | --- | --- |
cp .env.example .env.local | `npm run dev` | development | `.env.development` |
``` | `npm run build` | production | `.env.production` |
| `npm run preview` | 预览已有产物 | 使用构建时已写入的配置,不重新应用环境变量 |
```powershell 个人覆盖配置可写入 `.env.development.local` 或 `.env.production.local`(Git 忽略)。同名变量优先级从高到低:启动终端/CI > `.env.[mode].local` > `.env.[mode]` > `.env.local` > `.env`。旧的 `.env.local` 仍被加载,但与模式文件重名的变量会被模式文件覆盖,请迁移到对应的 `.local` 文件。可通过 Vite 的 `--mode` 显式选择其他模式。
# PowerShell
Copy-Item .env.example .env.local `.env.example` 原本只是示例,不会被 Vite 自动加载,现已移除。两个环境文件仅存公开默认值,修改后需重启开发服务或重新构建生产产物。
```
项目统一使用 npm,提交 package.json 与 package-lock.json。首次安装及 CI 使用 `npm ci`;有意更新依赖时使用 `npm install`,检查并提交锁文件变化。不要使用 Bun 或 Yarn 重新生成另一套锁文件。 项目统一使用 npm,提交 package.json 与 package-lock.json。首次安装及 CI 使用 `npm ci`;有意更新依赖时使用 `npm install`,检查并提交锁文件变化。不要使用 Bun 或 Yarn 重新生成另一套锁文件。
@@ -71,11 +71,11 @@ Copy-Item .env.example .env.local
/api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno /api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno
``` ```
其中 `/v1` 已启用 WebSocket 代理。连接远程测试后端时,修改集中定义的 `DEV_PROXY_TARGET`,然后重启开发服务;代理目标目前是写在配置文件中的,**没有读取专用的代理环境变量**。`package.json` 中的 `proxy` 字段不是这里的生效入口。 其中 `/v1` 已启用 WebSocket 代理。连接远程测试后端时,修改 `.env.development` 或 `.env.development.local` 中的 `DEV_PROXY_TARGET`,然后重启开发服务。该变量仅供 Vite 代理使用,不暴露给浏览器;默认保留原联调地址 `http://134.175.227.134:13000`。生产部署需由 Nginx/网关配置同源反向代理。`package.json` 中的 `proxy` 字段不是这里的生效入口。
### 可选:浏览器直接访问独立后端域名 ### 可选:浏览器直接访问独立后端域名
在 `.env.local` 中配置构建变量: 在 `.env.development` / `.env.production` 或对应的 `.local` 覆盖文件中配置构建变量:
```dotenv ```dotenv
VITE_REACT_APP_SERVER_URL=https://api.example.com VITE_REACT_APP_SERVER_URL=https://api.example.com
@@ -96,11 +96,11 @@ VITE_CLOUD_BRAIN_UI_ENABLED=false
| 配置 | 作用 | 生效方式 | | 配置 | 作用 | 生效方式 |
| --- | --- | --- | | --- | --- | --- |
| `VITE_CLOUD_BRAIN_UI_ENABLED` | 云脑套件入口与路由开关,默认关闭 | 构建时;修改后重启开发服务或重新构建 | | `VITE_CLOUD_BRAIN_UI_ENABLED` | 云脑套件入口与路由开关,默认关闭 | 构建时;修改后重启开发服务或重新构建 |
| `VITE_UMAMI_WEBSITE_ID` | 启用 Umami 统计脚本注入 | Vite 配置读取进程环境变量 | | `VITE_UMAMI_WEBSITE_ID` | 启用 Umami 统计脚本注入 | Vite 按当前 mode 加载环境文件,终端/CI 优先 |
| `VITE_UMAMI_SCRIPT_URL` | Umami 脚本地址 | 同上,默认 `https://analytics.umami.is/script.js` | | `VITE_UMAMI_SCRIPT_URL` | Umami 脚本地址 | 同上,默认 `https://analytics.umami.is/script.js` |
| `VITE_GOOGLE_ANALYTICS_ID` | 启用 Google Analytics 脚本注入 | 同上 | | `VITE_GOOGLE_ANALYTICS_ID` | 启用 Google Analytics 脚本注入 | 同上 |
统计脚本插件使用 `process.env`,没有显式调用 Vite `loadEnv`;如果使用 Node/npm 运行 Vite,不要假定只写 `.env.local` 就能让配置文件读到这些统计变量,应由启动终端或 CI 环境注入。 统计脚本插件与前端配置共用 Vite 环境加载规则;ID 留空时不注入脚本。生产统计 ID 通常只配置在 `.env.production` 或生产 CI 中。
前端构建变量会暴露给浏览器,仅放公开配置,不放上游模型密钥或后端机密。 前端构建变量会暴露给浏览器,仅放公开配置,不放上游模型密钥或后端机密。
+6 -12
View File
@@ -413,31 +413,25 @@ npm run dev
默认访问 `http://localhost:5173`;端口被占用时以终端输出为准。npm ci 不用于更新锁文件;清单与锁不一致时先定位差异。 默认访问 `http://localhost:5173`;端口被占用时以终端输出为准。npm ci 不用于更新锁文件;清单与锁不一致时先定位差异。
如果需要配置前端开关,再创建本地环境文件: 开发命令自动加载 `.env.development`,生产构建自动加载 `.env.production`。个人覆盖配置使用 `.env.development.local` / `.env.production.local`,这些文件已被 Git 忽略。环境变量优先级和迁移说明见 [README](../README.md#3-后端联调与环境配置)。新增或更新依赖时,统一使用团队约定的包管理器,同步检查 `package.json` 与 `package-lock.json`。
```powershell
Copy-Item .env.example .env.local
```
`.env.local` 已被 Git 忽略。新增或更新依赖时,统一使用团队约定的包管理器,同步检查 `package.json` 与 `package-lock.json`。
### 7.3 推荐联调方式:浏览器同源请求 ### 7.3 推荐联调方式:浏览器同源请求
不设置 `VITE_REACT_APP_SERVER_URL`(或设为空字符串),接口默认使用同源地址。 不设置 `VITE_REACT_APP_SERVER_URL`(或设为空字符串),接口默认使用同源地址。
此时前端向当前域名发请求,由 Vite 将以下路径转发到 `vite.config.js` 中 `DEV_PROXY_TARGET` 指定的后端(当前为远程地址 `http://134.175.227.134:13000`,不是本机 3000 端口): 此时前端向当前域名发请求,由 Vite 将以下路径转发到 `.env.development` 中 `DEV_PROXY_TARGET` 指定的后端(当前为远程地址 `http://134.175.227.134:13000`,不是本机 3000 端口):
```text ```text
/api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno /api /v1 /v1beta /mj /pg /dashboard /kling /jimeng /suno
``` ```
切换联调环境时,修改 `vite.config.js` 中集中定义的 `DEV_PROXY_TARGET` 并重启开发服务;各代理前缀共享这一目标。使用前确认该环境已获授权且适合测试,不在未知或生产环境执行破坏性操作。当前没有专门读取代理目标的环境变量,`package.json` 的 `proxy` 字段也不是 Vite 代理的生效入口。 切换联调环境时,修改 `.env.development` 或 `.env.development.local` 中的 `DEV_PROXY_TARGET` 并重启开发服务;各代理前缀共享这一目标。使用前确认该环境已获授权且适合测试,不在未知或生产环境执行破坏性操作。代理变量仅供 Vite 服务使用,不注入浏览器,`package.json` 的 `proxy` 字段也不是 Vite 代理的生效入口。
同源代理通常可以减少本地跨域联调问题,但代理本身不能替代后端账号、会话和业务配置。 同源代理通常可以减少本地跨域联调问题,但代理本身不能替代后端账号、会话和业务配置。
### 7.4 可选联调方式:直接连接独立后端 ### 7.4 可选联调方式:直接连接独立后端
在 `.env.local` 中配置后端根地址(构建变量): 在 `.env.development` / `.env.production` 或对应的 `.local` 文件中配置后端根地址(构建变量):
```dotenv ```dotenv
VITE_REACT_APP_SERVER_URL=https://api.example.com VITE_REACT_APP_SERVER_URL=https://api.example.com
@@ -563,7 +557,7 @@ npm run preview
| 部分说明落后于源码 | 体验中心子目录 README 仍使用 `web/src` 并描述图片、视频为占位功能 | 阅读时以当前入口、Hook 和接口调用为准 | | 部分说明落后于源码 | 体验中心子目录 README 仍使用 `web/src` 并描述图片、视频为占位功能 | 阅读时以当前入口、Hook 和接口调用为准 |
| 分层与命名存在历史差异 | `context/` 与 `contexts/` 并存,部分页面直接请求接口 | 新改动保持局部一致,按业务收益渐进整理,避免无目标的大规模搬迁 | | 分层与命名存在历史差异 | `context/` 与 `contexts/` 并存,部分页面直接请求接口 | 新改动保持局部一致,按业务收益渐进整理,避免无目标的大规模搬迁 |
统计脚本也是一个配置细节:Vite 插件使用 `process.env.VITE_UMAMI_WEBSITE_ID`、`VITE_UMAMI_SCRIPT_URL`、`VITE_GOOGLE_ANALYTICS_ID`,没有显式调用 `loadEnv`。使用 Node/npm 运行时,不要假定仅写入 `.env.local` 就一定能被配置文件读取;应由启动环境或 CI 注入并检查构建 HTML。 统计脚本由 Vite 的 `loadEnv` 按当前 mode 读取 `VITE_UMAMI_WEBSITE_ID`、`VITE_UMAMI_SCRIPT_URL`、`VITE_GOOGLE_ANALYTICS_ID`;支持开发/生产环境文件与本地覆盖文件,终端或 CI 的同名变量优先,ID 留空时禁用注入。
### 11.1 本次验证记录与结论边界 ### 11.1 本次验证记录与结论边界
@@ -615,7 +609,7 @@ Node 测试和生产构建通过不等于后端业务或线上发布验收通过
| 构建、代理与路径别名 | [vite.config.js](../vite.config.js)、[jsconfig.json](../jsconfig.json) | | 构建、代理与路径别名 | [vite.config.js](../vite.config.js)、[jsconfig.json](../jsconfig.json) |
| React 启动与布局 | [index.jsx](../src/index.jsx)、[PageLayout.jsx](../src/components/layout/PageLayout.jsx) | | React 启动与布局 | [index.jsx](../src/index.jsx)、[PageLayout.jsx](../src/components/layout/PageLayout.jsx) |
| 顶层路由与权限 | [App.jsx](../src/App.jsx)、[auth.jsx](../src/helpers/auth.jsx) | | 顶层路由与权限 | [App.jsx](../src/App.jsx)、[auth.jsx](../src/helpers/auth.jsx) |
| 共享请求与配置 | [api.js](../src/helpers/api.js)、[config.js](../src/helpers/config.js)、[环境变量示例](../.env.example) | | 共享请求与配置 | [api.js](../src/helpers/api.js)、[config.js](../src/helpers/config.js)、[开发环境](../.env.development)、[生产环境](../.env.production) |
| 请求去重 | [requestDedupe.js](../src/helpers/requestDedupe.js)、[相关测试](../src/helpers/requestDedupe.test.js) | | 请求去重 | [requestDedupe.js](../src/helpers/requestDedupe.js)、[相关测试](../src/helpers/requestDedupe.test.js) |
| 登录状态 | [User Provider](../src/context/User/index.jsx)、[User Reducer](../src/context/User/reducer.js) | | 登录状态 | [User Provider](../src/context/User/index.jsx)、[User Reducer](../src/context/User/reducer.js) |
| 企业入口与成员逻辑 | [Organization](../src/pages/Organization/index.jsx)、[useOrgMembers](../src/hooks/org/useOrgMembers.js) | | 企业入口与成员逻辑 | [Organization](../src/pages/Organization/index.jsx)、[useOrgMembers](../src/hooks/org/useOrgMembers.js) |
+1 -1
View File
@@ -152,7 +152,7 @@ loadUsers(0, pageSize)
- 删除 `public/config.js`。 - 删除 `public/config.js`。
- 删除 `index.html` 中的 `<script src="/config.js"></script>`。 - 删除 `index.html` 中的 `<script src="/config.js"></script>`。
- `getServerURL()` 不再访问 `window.__APP_CONFIG__`,只读取构建变量并回退到同源。 - `getServerURL()` 不再访问 `window.__APP_CONFIG__`,只读取构建变量并回退到同源。
- `.env.example` 增加后端地址示例,`src/helpers/config.test.js` 覆盖缺省、空值、绝对地址以及 HTML 不再加载旧脚本。 - 环境配置提供后端地址(现使用 `.env.development` / `.env.production`,原 `.env.example` 已移除),`src/helpers/config.test.js` 覆盖缺省、空值、绝对地址以及 HTML 不再加载旧脚本。
现在的地址选择只有两级: 现在的地址选择只有两级:
+146
View File
@@ -0,0 +1,146 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import assert from 'node:assert/strict';
import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
import { loadConfigFromFile, loadEnv, createServer } from 'vite';
const root = fileURLToPath(new URL('../', import.meta.url));
const html = '<!--umami--><!--Google Analytics-->';
async function fixture(run) {
const dir = await mkdtemp(path.join(root, '.env-test-'));
try {
await writeFile(
path.join(dir, 'vite.config.js'),
await readFile(path.join(root, 'vite.config.js')),
);
await writeFile(
path.join(dir, '.env.development'),
'DEV_PROXY_TARGET=http://localhost:13001\nVITE_REACT_APP_SERVER_URL=https://dev.example.com\nVITE_CLOUD_BRAIN_UI_ENABLED=true\nVITE_UMAMI_WEBSITE_ID=dev-id\nVITE_UMAMI_SCRIPT_URL=https://dev.example.com/script.js\n',
);
await writeFile(
path.join(dir, '.env.production'),
'VITE_REACT_APP_SERVER_URL=https://prod.example.com\nVITE_CLOUD_BRAIN_UI_ENABLED=false\nVITE_GOOGLE_ANALYTICS_ID=G-PROD\n',
);
await run(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
async function config(dir, mode) {
return (
await loadConfigFromFile(
{ command: mode === 'development' ? 'serve' : 'build', mode },
path.join(dir, 'vite.config.js'),
)
).config;
}
function analytics(config) {
return config.plugins
.find((plugin) => plugin.name === 'inject-analytics')
.transformIndexHtml(html);
}
test('development and production isolate API, feature flag and analytics settings', async () => {
await fixture(async (dir) => {
const dev = await config(dir, 'development');
const prod = await config(dir, 'production');
assert.match(analytics(dev), /dev-id/);
assert.match(analytics(dev), /https:\/\/dev.example.com\/script.js/);
assert.doesNotMatch(analytics(dev), /G-PROD/);
assert.match(analytics(prod), /G-PROD/);
assert.doesNotMatch(analytics(prod), /dev-id/);
for (const proxy of Object.values(dev.server.proxy)) {
assert.equal(proxy.target, 'http://localhost:13001');
assert.equal(proxy.changeOrigin, true);
}
assert.equal(dev.server.proxy['/v1'].ws, true);
for (const [mode, url, flag] of [
['development', 'https://dev.example.com', 'true'],
['production', 'https://prod.example.com', 'false'],
]) {
const env = loadEnv(mode, dir);
assert.equal(env.VITE_REACT_APP_SERVER_URL, url);
assert.equal(env.VITE_CLOUD_BRAIN_UI_ENABLED, flag);
assert.equal(env.DEV_PROXY_TARGET, undefined);
}
});
});
test('mode local overrides and CI variables reach the Vite plugins and proxy', async () => {
await fixture(async (dir) => {
await writeFile(
path.join(dir, '.env.development.local'),
'DEV_PROXY_TARGET=http://localhost:13002\nVITE_UMAMI_WEBSITE_ID=local-id\n',
);
assert.match(analytics(await config(dir, 'development')), /local-id/);
assert.equal(
(await config(dir, 'development')).server.proxy['/api'].target,
'http://localhost:13002',
);
const previous = process.env.VITE_UMAMI_WEBSITE_ID;
try {
process.env.VITE_UMAMI_WEBSITE_ID = 'ci-id';
assert.match(analytics(await config(dir, 'development')), /ci-id/);
} finally {
if (previous === undefined) delete process.env.VITE_UMAMI_WEBSITE_ID;
else process.env.VITE_UMAMI_WEBSITE_ID = previous;
}
});
});
test('checked-in defaults preserve same-origin behavior and disable analytics', async () => {
for (const mode of ['development', 'production']) {
const env = loadEnv(mode, root);
assert.equal(env.VITE_REACT_APP_SERVER_URL, '');
assert.equal(env.VITE_CLOUD_BRAIN_UI_ENABLED, 'false');
assert.equal(analytics(await config(root, mode)), html);
}
});
test('development server transforms the HTML and runtime configuration modules', async () => {
const server = await createServer({
root,
server: { middlewareMode: true },
optimizeDeps: { noDiscovery: true, include: [] },
});
try {
const output = await server.transformIndexHtml(
'/',
await readFile(path.join(root, 'index.html'), 'utf8'),
);
assert.match(output, /@vite\/client/);
for (const url of [
'/src/helpers/config.js',
'/src/config/cloudBrainUi.js',
]) {
const transformed = await server.transformRequest(url);
assert.match(transformed.code, /VITE_CLOUD_BRAIN_UI_ENABLED/);
assert.doesNotMatch(transformed.code, /134\.175\.227\.134/);
}
} finally {
await server.close();
}
});
+79 -76
View File
@@ -20,14 +20,13 @@ For commercial licensing, please contact support@quantumnous.com
import path from 'node:path'; import path from 'node:path';
import react from '@vitejs/plugin-react'; import react from '@vitejs/plugin-react';
import pkg from '@douyinfe/vite-plugin-semi'; import pkg from '@douyinfe/vite-plugin-semi';
import { defineConfig, transformWithEsbuild } from 'vite'; import { defineConfig, loadEnv, transformWithEsbuild } from 'vite';
// @douyinfe/vite-plugin-semi 是 CommonJS 包,具名导出挂在 default 上。 // @douyinfe/vite-plugin-semi 是 CommonJS 包,具名导出挂在 default 上。
const { vitePluginSemi } = pkg; const { vitePluginSemi } = pkg;
/** /**
* 开发服务器代理统一指向的后端根地址。 * 未配置代理变量时保留原有联调地址,兼容自定义 mode。
* 切换联调环境时只需改这一处,不必逐个前缀修改。
*/ */
const DEV_PROXY_TARGET = 'http://134.175.227.134:13000'; const DEV_PROXY_TARGET = 'http://134.175.227.134:13000';
@@ -118,19 +117,18 @@ function jsxInJsPlugin() {
/** /**
* 向 index.html 注入统计脚本。 * 向 index.html 注入统计脚本。
* *
* 变量在 transformIndexHtml 执行时才读取,以保持原有的生效时机: * 使用当前 mode 的环境变量;启动终端或 CI 的同名变量优先。
* 由启动终端或 CI 注入进程环境变量,未提供对应 ID 时不做任何替换。 * 未提供对应 ID 时不注入脚本。
*/ */
function analyticsPlugin() { function analyticsPlugin(env) {
return { return {
name: 'inject-analytics', name: 'inject-analytics',
transformIndexHtml(html) { transformIndexHtml(html) {
let result = html; let result = html;
const umamiId = process.env.VITE_UMAMI_WEBSITE_ID; const umamiId = env.VITE_UMAMI_WEBSITE_ID;
const umamiUrl = const umamiUrl =
process.env.VITE_UMAMI_SCRIPT_URL || env.VITE_UMAMI_SCRIPT_URL || 'https://analytics.umami.is/script.js';
'https://analytics.umami.is/script.js';
if (umamiId) { if (umamiId) {
result = result.replace( result = result.replace(
'<!--umami-->', '<!--umami-->',
@@ -138,7 +136,7 @@ function analyticsPlugin() {
); );
} }
const gaId = process.env.VITE_GOOGLE_ANALYTICS_ID; const gaId = env.VITE_GOOGLE_ANALYTICS_ID;
if (gaId) { if (gaId) {
result = result.replace( result = result.replace(
'<!--Google Analytics-->', '<!--Google Analytics-->',
@@ -153,75 +151,80 @@ function analyticsPlugin() {
} }
// https://vitejs.dev/config/ // https://vitejs.dev/config/
export default defineConfig({ export default defineConfig(({ mode }) => {
resolve: { const env = loadEnv(mode, __dirname, ['VITE_', 'DEV_PROXY_']);
alias: { const proxyTarget = env.DEV_PROXY_TARGET || DEV_PROXY_TARGET;
'@': path.resolve(__dirname, './src'),
'~': path.resolve(__dirname, 'node_modules'), return {
'@douyinfe/semi-theme-default': path.resolve( resolve: {
__dirname, alias: {
'node_modules/@douyinfe/semi-theme-default', '@': path.resolve(__dirname, './src'),
), '~': path.resolve(__dirname, 'node_modules'),
}, '@douyinfe/semi-theme-default': path.resolve(
}, __dirname,
plugins: [ 'node_modules/@douyinfe/semi-theme-default',
jsxInJsPlugin(), ),
react(),
vitePluginSemi({
cssLayer: true,
}),
analyticsPlugin(),
],
optimizeDeps: {
// 强制重新预构建,避免依赖变更后命中陈旧的依赖缓存
force: true,
esbuildOptions: {
loader: {
'.js': 'jsx',
'.json': 'json',
}, },
}, },
}, plugins: [
build: { jsxInJsPlugin(),
// 使用 esbuild 压缩:速度远快于 terser,压缩率略低 react(),
minify: 'esbuild', vitePluginSemi({
// 启用 CSS 代码分割 cssLayer: true,
cssCodeSplit: true, }),
// chunk 体积告警阈值 (KB) analyticsPlugin(env),
chunkSizeWarningLimit: 1000, ],
// 构建目标为 es2015,以换取更广的浏览器兼容性 optimizeDeps: {
target: 'es2015', // 强制重新预构建,避免依赖变更后命中陈旧的依赖缓存
// 生产环境不需要 sourcemap force: true,
sourcemap: false, esbuildOptions: {
// esbuild 压缩选项:移除调试语句与版权注释 loader: {
esbuild: { '.js': 'jsx',
drop: ['console', 'debugger'], '.json': 'json',
legalComments: 'none', },
},
rollupOptions: {
output: {
// 文件名带内容 hash,便于浏览器长期缓存与增量更新
chunkFileNames: 'assets/[name]-[hash].js',
entryFileNames: 'assets/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash].[ext]',
manualChunks: resolveVendorChunk,
}, },
}, },
}, build: {
server: { // 使用 esbuild 压缩:速度远快于 terser,压缩率略低
// 监听所有网卡,便于局域网与容器内访问 minify: 'esbuild',
host: '0.0.0.0', // 启用 CSS 代码分割
proxy: { cssCodeSplit: true,
// 以下前缀统一转发到同一个后端,其中 /v1 额外开启 WebSocket // chunk 体积告警阈值 (KB)
'/api': { target: DEV_PROXY_TARGET, changeOrigin: true }, chunkSizeWarningLimit: 1000,
'/v1': { target: DEV_PROXY_TARGET, changeOrigin: true, ws: true }, // 构建目标为 es2015,以换取更广的浏览器兼容性
'/v1beta': { target: DEV_PROXY_TARGET, changeOrigin: true }, target: 'es2015',
'/mj': { target: DEV_PROXY_TARGET, changeOrigin: true }, // 生产环境不需要 sourcemap
'/pg': { target: DEV_PROXY_TARGET, changeOrigin: true }, sourcemap: false,
'/dashboard': { target: DEV_PROXY_TARGET, changeOrigin: true }, // esbuild 压缩选项:移除调试语句与版权注释
'/kling': { target: DEV_PROXY_TARGET, changeOrigin: true }, esbuild: {
'/jimeng': { target: DEV_PROXY_TARGET, changeOrigin: true }, drop: ['console', 'debugger'],
'/suno': { target: DEV_PROXY_TARGET, changeOrigin: true }, legalComments: 'none',
},
rollupOptions: {
output: {
// 文件名带内容 hash,便于浏览器长期缓存与增量更新
chunkFileNames: 'assets/[name]-[hash].js',
entryFileNames: 'assets/[name]-[hash].js',
assetFileNames: 'assets/[name]-[hash].[ext]',
manualChunks: resolveVendorChunk,
},
},
}, },
}, server: {
// 监听所有网卡,便于局域网与容器内访问
host: '0.0.0.0',
proxy: {
// 以下前缀统一转发到同一个后端,其中 /v1 额外开启 WebSocket
'/api': { target: proxyTarget, changeOrigin: true },
'/v1': { target: proxyTarget, changeOrigin: true, ws: true },
'/v1beta': { target: proxyTarget, changeOrigin: true },
'/mj': { target: proxyTarget, changeOrigin: true },
'/pg': { target: proxyTarget, changeOrigin: true },
'/dashboard': { target: proxyTarget, changeOrigin: true },
'/kling': { target: proxyTarget, changeOrigin: true },
'/jimeng': { target: proxyTarget, changeOrigin: true },
'/suno': { target: proxyTarget, changeOrigin: true },
},
},
};
}); });