Vite 提供了完善的 TypeScript 支持,开发者可以在 Vite 项目中无缝使用 TypeScript。以下是 Vite 中 TypeScript 的使用和配置方法:
基本支持:
Vite 开箱即支持 TypeScript,无需额外配置。可以直接使用 .ts、.tsx 文件,Vite 会自动处理类型检查和转译。
配置文件:
- tsconfig.json:TypeScript 配置文件
- vite.config.ts:Vite 配置文件(TypeScript 版本)
类型检查:
开发环境:
- Vite 默认不进行类型检查,以保持快速的开发体验
- 可以通过
vite-plugin-checker插件实现类型检查 - 或者在单独的进程中运行
tsc --noEmit
生产构建:
- Vite 构建时会使用 esbuild 进行转译
- esbuild 的类型检查功能有限,建议在 CI/CD 中运行
tsc
配置示例:
json// tsconfig.json { "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "module": "ESNext", "lib": ["ES2020", "DOM", "DOM.Iterable"], "skipLibCheck": true, "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] }
路径别名:
typescript// vite.config.ts import { defineConfig } from 'vite' import path from 'path' export default defineConfig({ resolve: { alias: { '@': path.resolve(__dirname, './src') } } })
json// tsconfig.json { "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] } } }
环境变量类型定义:
typescript// src/vite-env.d.ts interface ImportMetaEnv { readonly VITE_API_URL: string readonly VITE_APP_TITLE: string } interface ImportMeta { readonly env: ImportMetaEnv }
类型检查插件:
typescript// vite.config.ts import { defineConfig } from 'vite' import checker from 'vite-plugin-checker' export default defineConfig({ plugins: [ checker({ typescript: true, eslint: { lintCommand: 'eslint "./src/**/*.{ts,tsx}"' } }) ] })
最佳实践:
- 在开发环境中使用
vite-plugin-checker进行实时类型检查 - 在 CI/CD 流程中运行
tsc --noEmit确保类型安全 - 使用
strict模式启用所有严格类型检查 - 合理配置
skipLibCheck提升构建速度 - 为环境变量定义类型,避免类型错误