server.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import type { ServerOptions } from 'vite';
  2. /**
  3. * 开发服务器配置(含 API 代理)。依赖运行期 env(端口、代理目标),故以工厂函数导出。
  4. * 代理 /dev/api/v1 → VITE_DEV_PROXY_TARGET_API_BASE_URL,并 rewrite 掉前缀。
  5. * @param env 处理后的环境变量(wrapperEnv 产物)。
  6. */
  7. export function createServerOptions(env: ImportMetaEnv): ServerOptions {
  8. return {
  9. port: env.VITE_DEV_PORT,
  10. host: '0.0.0.0',
  11. open: true,
  12. proxy: {
  13. '/dev/api/v1': {
  14. target: env.VITE_DEV_PROXY_TARGET_API_BASE_URL,
  15. changeOrigin: true,
  16. rewrite: (path) => path.replace(/^\/dev\/api\/v1/, ''),
  17. secure: false,
  18. configure: (proxy) => {
  19. proxy.on('error', (err) => {
  20. console.log('proxy error', err);
  21. });
  22. proxy.on('proxyReq', (_, req) => {
  23. console.log(
  24. 'Sending Request to the Target:',
  25. req.method,
  26. req.url,
  27. env.VITE_DEV_PROXY_TARGET_API_BASE_URL
  28. );
  29. });
  30. proxy.on('proxyRes', (proxyRes, req) => {
  31. console.log(
  32. 'Received Response from the Target:',
  33. proxyRes.statusCode,
  34. req.url
  35. );
  36. });
  37. },
  38. },
  39. },
  40. warmup: {
  41. clientFiles: ['./index.html', './src/{pages,components}/*'],
  42. },
  43. };
  44. }