Vite 如何支持 TypeScript?如何配置类型检查?
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配置示例:// 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" }]}路径别名:// vite.config.tsimport { defineConfig } from 'vite'import path from 'path'export default defineConfig({ resolve: { alias: { '@': path.resolve(__dirname, './src') } }})// tsconfig.json{ "compilerOptions": { "baseUrl": ".", "paths": { "@/*": ["src/*"] } }}环境变量类型定义:// src/vite-env.d.tsinterface ImportMetaEnv { readonly VITE_API_URL: string readonly VITE_APP_TITLE: string}interface ImportMeta { readonly env: ImportMetaEnv}类型检查插件:// vite.config.tsimport { 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 提升构建速度为环境变量定义类型,避免类型错误