vite.config.ts 1.42 KB
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

// Dev: Vite serves the SPA on :5173 and proxies API/SSE to the CodeRio
// backend on :4173. Prod: the backend serves `dist/` directly (same origin),
// so no proxy is needed.
export default defineConfig({
  plugins: [react()],
  resolve: {
    alias: { '@': path.resolve(__dirname, './src') },
  },
  server: {
    port: 5173,
    // 绑定 IPv4,确保 127.0.0.1 与 localhost 均可访问(Windows 上 localhost
    // 默认优先 ::1,会导致 127.0.0.1 直连代理/SSE 时失败)。
    host: '127.0.0.1',
    proxy: {
      '/api': {
        // 用 127.0.0.1 而非 localhost:Windows 上 localhost 默认优先解析 IPv6(::1),
        // 而后端仅监听 IPv4,会导致间歇 ECONNREFUSED(Vite 自身也绑 127.0.0.1)。
        target: 'http://127.0.0.1:4173',
        changeOrigin: true,
      },
      // supervisor 控制端口(scripts/dev.mjs):后端启动/停止/重启。
      // 它独立于后端常驻,因此「停止后端」后前端仍能向其发启动指令。
      '/devctl': {
        target: 'http://127.0.0.1:4174',
        changeOrigin: true,
        rewrite: (p) => p.replace(/^\/devctl/, ''),
      },
    },
  },
  build: {
    outDir: 'dist',
    sourcemap: false,
  },
});