import { defineConfig, mergeConfig, loadEnv } from 'vite' import { dirname, resolve } from 'path' import { fileURLToPath } from 'url' import baseViteConfig from './vite.config' const __dirname = dirname(fileURLToPath(import.meta.url)) /** 代理只能用「协议+主机+端口」,不能带 path;否则转发路径容易错 */ function devProxyTarget(apiBaseUrl) { if (!apiBaseUrl || typeof apiBaseUrl !== 'string') { return '' } try { const u = new URL(apiBaseUrl) return `${u.protocol}//${u.host}` } catch { return '' } } // 与 portal-ui 根目录一致加载 .env*(ESM 下必须用 import.meta.url,不能依赖未定义的 __dirname) const env = loadEnv('development', resolve(__dirname)) const apiBase = env.VITE_API_URL?.trim() || '' const proxyTarget = devProxyTarget(apiBase) if (!proxyTarget) { console.warn( '[vite] VITE_API_URL 未配置或无效,/dev-api 代理未启用。请在 .env.development 中设置,例如:VITE_API_URL=http://47.86.170.114:8011/api' ) } const devConfig = defineConfig({ server: { host: env.VITE_HOST || 'localhost', port: Number(env.VITE_PORT) || 8081, open: true, watch: { ignored: [/node_modules/, /dist/, /deploy/] }, ...(proxyTarget ? { proxy: { '/dev-api': { target: proxyTarget, ws: false, changeOrigin: true, rewrite: (path) => path.replace(/^\/dev-api/, '') } } } : {}) } }) export default mergeConfig(baseViteConfig, devConfig)