全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-23 6 分钟 ✍️ juanwangdev

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 中同步设置。

关键配置项

配置项说明
moduleResolutionbundlerVite 模块解析方式
isolatedModulestrue每个文件作为独立模块
allowImportingTsExtensionstrue允许导入 .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 配置

📝 发现内容有误?点击此处直接编辑

← 上一篇 Vue/React 类型支持
下一篇 → esbuild 转译配置
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库