乐闻世界logo
搜索文章和话题

Vite 如何支持 TypeScript?如何配置类型检查?

2月19日 19:14

Vite 提供了完善的 TypeScript 支持,开发者可以在 Vite 项目中无缝使用 TypeScript。以下是 Vite 中 TypeScript 的使用和配置方法:

基本支持

Vite 开箱即支持 TypeScript,无需额外配置。可以直接使用 .ts.tsx 文件,Vite 会自动处理类型检查和转译。

配置文件

  1. tsconfig.json:TypeScript 配置文件
  2. 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}"' } }) ] })

最佳实践

  1. 在开发环境中使用 vite-plugin-checker 进行实时类型检查
  2. 在 CI/CD 流程中运行 tsc --noEmit 确保类型安全
  3. 使用 strict 模式启用所有严格类型检查
  4. 合理配置 skipLibCheck 提升构建速度
  5. 为环境变量定义类型,避免类型错误
标签:Vite