nex_buddy/web/vite.config.ts

52 lines
1.8 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// 端口唯一来源是项目根的 .env:BACKEND_PORT / FRONTEND_PORT。
// scripts/dev.sh(后端)和这里(前端)都读同一份,改端口只改 .env 一处。
function readRootEnv(): Record<string, string> {
const out: Record<string, string> = {}
try {
const txt = readFileSync(fileURLToPath(new URL('../.env', import.meta.url)), 'utf-8')
for (const raw of txt.split('\n')) {
const line = raw.trim()
if (!line || line.startsWith('#')) continue
const eq = line.indexOf('=')
if (eq <= 0) continue
out[line.slice(0, eq).trim()] = line.slice(eq + 1).trim().replace(/^["']|["']$/g, '')
}
} catch {
// 根目录没有 .env 时用默认端口
}
return out
}
const env = readRootEnv()
const BACKEND_PORT = Number(env.BACKEND_PORT) || 8000
const FRONTEND_PORT = Number(env.FRONTEND_PORT) || 5173
const proxy = {
'/api': { target: `http://127.0.0.1:${BACKEND_PORT}`, changeOrigin: true },
'/device': { target: `http://127.0.0.1:${BACKEND_PORT}`, changeOrigin: true },
'/healthz': { target: `http://127.0.0.1:${BACKEND_PORT}`, changeOrigin: true },
}
export default defineConfig({
plugins: [react()],
server: {
port: FRONTEND_PORT,
// 默认只监听 [::1],127.0.0.1 会连不上;顺便让手机在同一局域网也能打开调试
host: '0.0.0.0',
proxy,
},
// 本地用打包产物验证「手机扫设备屏二维码」这条链路:dev 的按需编译
// 在局域网 IP 下会被浏览器的跨网络限制挡住,而线上是静态文件。
// 端口同用 FRONTEND_PORT;若 dev server 正在跑被占用,vite 会自动顺延
preview: {
port: FRONTEND_PORT,
host: '0.0.0.0',
proxy,
},
})