如何在Vite(Preact-ts模板)中共享后端TypeScript类型?
前端Vite与后端Express共享TypeScript类型的解决方案
1. 同步Vite的别名配置
Vite不会自动读取tsconfig.json中的paths配置,需要在vite.config.ts里手动配置别名,确保Vite能正确解析路径:
import { defineConfig } from 'vite'; import preact from '@preact/preset-vite'; import path from 'path'; export default defineConfig({ plugins: [preact()], resolve: { alias: { 'types': path.resolve(__dirname, '../backend/types'), 'types/*': path.resolve(__dirname, '../backend/types/*'), }, }, });
2. 修正TypeScript配置
2.1 调整路径匹配规则
更新tsconfig.json的paths配置,添加通配符支持子路径导入,同时让TS编译器能识别后端类型文件:
{ "compilerOptions": { "baseUrl": ".", "paths": { "types": ["../backend/types"], "types/*": ["../backend/types/*"] }, // 其余原有配置保持不变 "target": "ESNext", "useDefineForClassFields": true, "lib": ["DOM", "DOM.Iterable", "ESNext"], "allowJs": false, "skipLibCheck": true, "esModuleInterop": false, "allowSyntheticDefaultImports": true, "strict": true, "forceConsistentCasingInFileNames": true, "module": "ESNext", "moduleResolution": "Node", "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "jsxImportSource": "preact" }, "include": ["src", "../backend/types/**/*"], "references": [{ "path": "./tsconfig.node.json" }] }
2.2 关键说明
原来的include仅包含前端src目录,TS编译器无法读取后端类型文件,必须把../backend/types/**/*加入include数组,让类型文件被TS识别。
3. 验证导入有效性
现在可以在前端代码中正常导入并使用后端类型:
import { TestInterface } from 'types'; // 测试类型校验是否生效 const testData: TestInterface = { test: "demo", test2: 456 };
常见排查点
- 核对相对路径:确认
../backend/types是后端类型目录的正确相对路径,根据实际项目结构调整。 - 重启开发服务:修改配置后必须重启Vite开发服务器,确保新配置生效。
- 检查导出逻辑:确认后端
types/index.ts及子目录的导出语句无拼写错误,所有需要的接口都已正确导出。
内容的提问来源于stack exchange,提问作者rearwindowsoda
相关产品推荐
相关产品推荐

