TypeScript 配置优化
Vite 与 TypeScript 需要正确配置才能协同工作,确保路径解析和类型检查一致。
基础 tsconfig.json
JSON
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM"],
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}
路径别名同步
JavaScript
// vite.config.js
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
}
})
JSON
// tsconfig.json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
注意:别名配置需在 vite.config.js 和 tsconfig.json 中同步设置。
关键配置项
| 配置项 | 值 | 说明 |
|---|---|---|
| moduleResolution | bundler | Vite 模块解析方式 |
| isolatedModules | true | 每个文件作为独立模块 |
| allowImportingTsExtensions | true | 允许导入 .ts 文件 |
引用 Vite 类型
JSON
{
"compilerOptions": {
"types": ["vite/client"]
}
}
或使用三斜线指令:
TypeScript
/// <reference types="vite/client" />
配置分离
JSON
tsconfig.json # 主配置
tsconfig.node.json # Node 端配置(vite.config.ts)
text
// tsconfig.json
{
"references": [
{ "path": "./tsconfig.node.json" }
]
}
// tsconfig.node.json
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "bundler"
},
"include": ["vite.config.ts"]
}
要点总结
- moduleResolution 设为 bundler
- 路径别名需同步配置
- 引用 vite/client 类型声明
- 使用 references 分离 Node 配置
📝 发现内容有误?点击此处直接编辑