import { readFileSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import vue from '@vitejs/plugin-vue'; import { parse } from 'dotenv'; import { defineConfig } from 'vite'; const webDirectory = path.dirname(fileURLToPath(import.meta.url)); const developmentEnvFile = path.resolve(webDirectory, '../deploy/env/development/web.env.local'); function readDevelopmentPublicEnv() { if (process.env.NODE_ENV === 'production') return {}; try { return Object.fromEntries( Object.entries(parse(readFileSync(developmentEnvFile))).filter(([key]) => key.startsWith('VITE_'), ), ); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {}; throw error; } } const publicEnv = readDevelopmentPublicEnv(); export default defineConfig({ plugins: [vue()], define: Object.fromEntries( Object.entries(publicEnv).map(([key, value]) => [ `import.meta.env.${key}`, JSON.stringify(value), ]), ), server: { host: '127.0.0.1', port: 5173, strictPort: true, proxy: { // 本地浏览器始终请求同源 /api,由 Vite 转发到 NestJS,避免开发环境放宽 CORS。 '/api': { target: 'http://127.0.0.1:3000', changeOrigin: false, }, }, }, });