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: true:arr[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 fields、top-level await、Error Cause都覆盖module: NodeNext—— Node 项目的现代选择strict: true—— 一次性打开 8 个严格检查,等价于:noImplicitAnystrictNullChecksstrictFunctionTypesstrictBindCallApplystrictPropertyInitializationnoImplicitThisuseUnknownInCatchVariablesalwaysStrict
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+、现代浏览器都支持 ES2022experimentalDecorators—— TC39 标准装饰器已稳定(TS 5.0+),用新写法importHelpers—— tslib 已经过时,TS 5.0+ 自动处理
文件选项
{
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
三个字段的取舍:
| 字段 | 作用 | 优先级 |
|---|---|---|
files | 显式列举 | 最高 |
include | glob 匹配 | 中 |
exclude | 排除(对 include 生效) | 最低 |
tip
files 显式指定的文件总是被编译,不受 exclude 影响。新项目用 include + exclude 组合就够了。
工程引用(monorepo)
tsconfig.json 用 references 字段拆分子项目:
├── 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
- TypeScript Handbook: tsconfig.json —— 官方手册
- TypeScript tsconfig reference —— 所有选项的完整参考
- TypeScript 5.0 Release Notes ——
verbatimModuleSyntax等新选项的引入