02 · Vite 启动与 dev server

0 阅读2分钟

本项目配置见 ../frontend/vite.config.ts

2.1 Failed to resolve import "xxx" from "src/yyy"

高频原因:

  • 路径别名未配置或拼错:本项目 @ 指向 frontend/src,见 vite.config.ts:8
  • 文件扩展名问题:import './foo' 实际是 foo.tsx,需要 vite 自动补全
  • 大小写敏感:Windows 不敏感、Linux/CI 敏感,本地正常 CI 挂

定位:

  • 终端打印 Failed to resolve import "X" from "Y". Does the file exist?
  • 在 IDE 里 Ctrl+点击 import 路径,跳不过去就是有问题

解决:

  • @/components/Foo 绝对引用代替深层相对路径 ../../../components/Foo
  • 统一文件名大小写(组件用 PascalCase、工具用 camelCase,团队约定一种)

2.2 [plugin:vite:import-analysis] Failed to parse source

原因:文件里有语法错误,但 sourcemap 指向不准。

定位:看终端 at xx:line:col,常见原因:

  • JSX 标签未闭合
  • return 后写了多行 JSX 没用 () 包裹
  • TS 语法用在 .js 文件里

2.3 浏览器白屏,控制台报 Uncaught SyntaxError: Unexpected token '<'

原因:public 路径 / base 配置错误,index.html 引用的 /src/main.tsx 被服务器当成 HTML 返回。

定位:Network 面板看 main.tsx 响应的 Content-Type;若是 text/html,说明 SPA 兜底路由把它拦截了。

解决:

  • 检查反向代理 / base 配置
  • dev 模式确认是 Vite serve 而不是 nginx 在前面
  • 部署到子路径时 defineConfig({ base: '/app/' }),见 06-构建打包与部署.md

2.4 代理不生效:/api/xxx 报 404 或 CORS

原因:vite.config.ts:12-15 的 proxy 只对 dev server 生效,生产环境需要 nginx 转发。

定位:

  • Network 中请求 URL 是 http://localhost:5173/api/...(走代理)还是 http://localhost:9002/...(直连)?
  • axios baseURL 配错会导致直连后端,触发 CORS

解决:

  • 统一通过相对路径 /api/xxx,走 Vite 代理
  • 生产环境 nginx 配 location /api { proxy_pass http://backend; }

2.5 WebSocket 连不上:WebSocket connection to 'ws://...' failed

原因:本项目使用 Yjs 协同 + WebRTC,需要 ws 代理。

定位:

  • vite.config.ts:14 是否启用了 ws: true?
  • 检查 token / 鉴权头是否在握手阶段被丢弃

解决:

  • wss 必须 changeOrigin: true
  • 鉴权用 query param 而非 header,因为浏览器 WebSocket API 不支持自定义握手 header
  • 也见 09-Yjs协同.md

2.6 optimized dependencies changed. reloading. 无限刷新

原因:Vite 预构建依赖被反复触发,通常是动态 import 路径变化或 optimizeDeps.include 缺失。

解决:

rm -rf node_modules/.vite

vite.config.ts 显式声明:

optimizeDeps: { include: ['antd', 'echarts', 'echarts-for-react'] }

2.7 端口被占用:Port 5173 is in use, trying another one...

说明:Vite 自动换端口,但代理目标和文档(../运行指南.md)写死 5173 时,会导致后续访问错乱。

解决:

  • 杀掉占用进程:Windows netstat -ano | findstr 5173taskkill /F /PID xxx
  • 或在 vite.config.ts 加 server: { strictPort: true },占用就直接报错

2.8 import.meta.glob 路径模式不匹配

现象:import.meta.glob('./pages/*.tsx') 返回空对象。

原因:

  • 路径必须以 .// 开头,不能用 @/
  • Glob 模式不支持别名

解决:用相对路径,或 import.meta.glob('/src/pages/*.tsx')(从项目根开始)。