Skip to content
第 17 章 前端 ⏱ 12 分钟阅读

第 17 章:tsconfig 配置 ​

学习目标 ​

  • 理解 tsconfig.json 的整体结构
  • 掌握 compilerOptions 关键选项
  • 学会项目分层配置(extends)
  • 避开常见配置错误

一、最小配置 ​

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "strict": true
  },
  "include": ["src/**/*"]
}

二、target 与 module ​

json
{
  "compilerOptions": {
    "target": "ES2020",        // 编译到哪个 JS 版本
    "module": "ESNext",        // 模块系统
    "moduleResolution": "bundler",
    "lib": ["ES2020", "DOM", "DOM.Iterable"]
  }
}
场景targetmodulemoduleResolution
现代 Vite 项目ES2020 或 ES2022ESNextbundler
Node.js 库ES2020ESNext / CommonJSnode16
老浏览器ES5ES5node

⚠️ 坑 1:module 和 moduleResolution 必须配套,ESNext 必须配 bundler,CommonJS 必须配 node。

三、严格模式(strict) ​

json
{
  "compilerOptions": {
    "strict": true
  }
}

strict: true 等价于同时开启:

json
{
  "compilerOptions": {
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictBindCallApply": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "useUnknownInCatchVariables": true
  }
}

四、输出配置 ​

json
{
  "compilerOptions": {
    "outDir": "./dist",          // 输出目录
    "rootDir": "./src",          // 源码根目录
    "declaration": true,         // 生成 .d.ts
    "declarationMap": true,      // 生成 .d.ts.map(源码映射)
    "sourceMap": true,           // 生成 .js.map
    "removeComments": false      // 保留注释
  }
}

⚠️ 坑 2:rootDir 配置错误会导致编译时"找不到文件"或"输出结构混乱"。

五、路径解析(paths) ​

json
{
  "compilerOptions": {
    "baseUrl": "./",
    "paths": {
      "@/*": ["src/*"],
      "@utils/*": ["src/utils/*"],
      "@components/*": ["src/components/*"]
    }
  }
}
typescript
import { Button } from '@components/Button';  // → src/components/Button
import { add } from '@utils/math';             // → src/utils/math

⚠️ 坑 3:Vite / webpack 也需要配别名(tsc 的 paths 只影响类型检查,不参与打包)。Vite 项目需要 vite.config.ts 里同时配 resolve.alias。

六、include / exclude / files ​

json
{
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist", "**/*.test.ts"],
  "files": ["src/index.ts"]
}
  • include:要参与编译的文件
  • exclude:排除
  • files:显式指定(优先级最高)

七、检查项常用选项 ​

json
{
  "compilerOptions": {
    "noUnusedLocals": true,            // 禁止未使用的局部变量
    "noUnusedParameters": true,       // 禁止未使用的参数
    "noFallthroughCasesInSwitch": true,
    "noImplicitReturns": true,         // 函数必须显式 return
    "noUncheckedIndexedAccess": true,  // 数组下标访问返回 T | undefined
    "exactOptionalPropertyTypes": true // 可选字段不能显式赋 undefined
  }
}

⚠️ 坑 4:noUncheckedIndexedAccess 开启后 arr[0] 永远是 T | undefined,能避免很多数组越界 bug,但需要大量代码适配。

八、ESBuild / SWC 配合 ​

现代项目常用 esbuild / swc 转译:

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "ESNext",
    "isolatedModules": true,    // 单文件也能编译
    "noEmit": true              // tsc 只检查,不输出
  }
}
bash
tsc --noEmit         # 类型检查
esbuild src/index.ts --bundle --outfile=dist/index.js   # 打包

九、配置分层继承 ​

json
// tsconfig.base.json
{
  "compilerOptions": {
    "target": "ES2020",
    "strict": true
  }
}

// tsconfig.json
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "module": "ESNext"
  }
}

⚠️ 坑 5:extends 只继承 compilerOptions,include / files 不继承。

十、Vite + TS 完整配置 ​

json
// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "moduleResolution": "bundler",
    "strict": true,
    "jsx": "preserve",
    "sourceMap": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,
    "noEmit": true,
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "baseUrl": ".",
    "paths": { "@/*": ["src/*"] }
  },
  "include": ["src/**/*.ts", "src/**/*.tsx"]
}

十一、本章小结 ​

选项作用
target编译到哪个 JS 版本
module / moduleResolution模块系统和解析方式
strict严格模式总开关
paths路径别名
include / exclude参与编译的文件
declaration是否生成 .d.ts
isolatedModules单文件编译兼容

动手练习 ​

  1. 最小配置:新建项目,写最小可用的 tsconfig.json
  2. 路径别名:配 @/* 映射到 src/*,验证 import 是否生效
  3. 严格模式:开 strict: true,故意写错看报错信息

下一章:第 18 章:类型实战 →

本站基于 VitePress 构建 · 由 StackHub 团队维护