Skip to main content

tsconfig.json 必开配置:2026 版速查

· 3 min read

tsconfig.json 选项有 100+ 个,但日常 80% 场景只需要 10 个左右

  • strict: true:8 个严格检查全开,新项目必开
  • target: "ES2022":覆盖 Node 18+ 和现代浏览器
  • module: "NodeNext":Node ESM 现代写法
  • skipLibCheck: true:跳过 .d.ts 检查,构建快 30%+
  • noUncheckedIndexedAccess: truearr[0] 类型变 T | undefined

必开配置(2026 年推荐)

{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
"noFallthroughCasesInSwitch": true,
"exactOptionalPropertyTypes": true
}
}

每一项的理由:

  • target: ES2022 —— class fieldstop-level awaitError Cause 都覆盖
  • module: NodeNext —— Node 项目的现代选择
  • strict: true —— 一次性打开 8 个严格检查,等价于:
    • noImplicitAny
    • strictNullChecks
    • strictFunctionTypes
    • strictBindCallApply
    • strictPropertyInitialization
    • noImplicitThis
    • useUnknownInCatchVariables
    • alwaysStrict
  • esModuleInterop —— 让 import React from 'react' 正常工作
  • skipLibCheck —— 跳过 @types/* 包的类型检查,构建快很多
  • noUncheckedIndexedAccess —— arr[0] 类型变成 T | undefined,强制处理边界
  • verbatimModuleSyntax —— import 时必须明确写 import type

已过时的选项

warning

以下选项在新项目里不要再用

  • module: "CommonJS" —— 现代 Node ESM 是默认,写 "NodeNext" 让 TS 自动判断
  • moduleResolution: "Node" —— "NodeNext""Bundler" 是更新版
  • target: "ES5" —— Node 18+、现代浏览器都支持 ES2022
  • experimentalDecorators —— TC39 标准装饰器已稳定(TS 5.0+),用新写法
  • importHelpers —— tslib 已经过时,TS 5.0+ 自动处理

文件选项

{
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}

三个字段的取舍:

字段作用优先级
files显式列举最高
includeglob 匹配
exclude排除(对 include 生效)最低
tip

files 显式指定的文件总是被编译,不受 exclude 影响。新项目用 include + exclude 组合就够了。


工程引用(monorepo)

tsconfig.jsonreferences 字段拆分子项目:

├── packages
│ ├── core
│ │ ├── tsconfig.json
│ │ └── src/index.ts
│ └── web
│ ├── tsconfig.json
│ └── src/index.ts
├── tsconfig.json // 根配置

tsconfig.json

{
"files": [],
"references": [
{ "path": "./packages/core" },
{ "path": "./packages/web" }
]
}

子项目 tsconfig.json

{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"composite": true,
"outDir": "./dist"
},
"include": ["src/**/*"]
}

构建用 tsc -b

tsc -b packages/core # 单包构建
tsc -b # 全量构建(自动按依赖顺序)

References

  1. TypeScript Handbook: tsconfig.json —— 官方手册
  2. TypeScript tsconfig reference —— 所有选项的完整参考
  3. TypeScript 5.0 Release Notes —— verbatimModuleSyntax 等新选项的引入