TypeScript 配置文件 (tsconfig.json) 终极指南
一、配置文件核心意义
tsconfig.json 是 TypeScript 项目的核心配置文件,用于定义 TypeScript 编译器(tsc)的编译规则、类型检查策略、输出行为等。当在项目根目录执行 tsc 命令时,编译器会自动读取该文件并应用配置;若未指定 tsconfig.json,编译器将使用默认规则。
二、完整配置项详解(无遗漏版)
2.1 顶层基础配置
| 配置项 | 类型 | 默认值 | 详细说明 |
|---|---|---|---|
compilerOptions | object | - | 编译器核心配置(所有编译相关规则均在此节点下) |
include | string[] | ["**/*"] | 指定需要编译的文件/目录,支持 glob 通配符(如 src/**/*.ts、src/**/*.tsx) |
exclude | string[] | ["node_modules", "bower_components", "jspm_packages"] | 指定排除编译的文件/目录,优先级高于 include,可自定义添加 dist、build 等 |
files | string[] | - | 显式指定需要编译的单个文件列表(优先级最高,适用于少量文件的项目) |
extends | string | - | 继承外部 tsconfig 配置(支持相对路径或 npm 包,如 @tsconfig/node20/tsconfig.json) |
references | object[] | - | 项目引用配置,用于 Monorepo 多项目依赖场景,实现增量编译和类型隔离 |
typeAcquisition | object | { "enable": false, "include": [], "exclude": [] } | 自动类型获取配置(针对未安装 @types 的第三方库) |
compileOnSave | boolean | false | 编辑器保存时自动编译(需编辑器支持,如 VS Code) |
watchOptions | object | - | 监听模式(tsc --watch)的配置项,控制文件监听行为 |
2.2 watchOptions 子配置(监听模式)
| 配置项 | 类型 | 默认值 | 详细说明 |
|---|---|---|---|
watchFile | string | useFsEvents | 文件监听方式: - useFsEvents:使用系统文件监听(推荐) - useFsEventsOnParentDirectory:监听父目录 - fixedPollingInterval:固定轮询 - priorityPollingInterval:优先级轮询 |
watchDirectory | string | useFsEvents | 目录监听方式(同 watchFile 取值) |
fallbackPolling | string | fixedPollingInterval | 监听降级策略(文件监听失败时使用) |
synchronousWatchDirectory | boolean | false | 同步监听目录变化(避免竞态条件) |
excludeDirectories | string[] | - | 排除监听的目录(如 ["node_modules", "dist"]) |
excludeFiles | string[] | - | 排除监听的文件(如 ["**/*.log", "**/*.tmp"]) |
2.3 typeAcquisition 子配置(自动类型获取)
| 配置项 | 类型 | 默认值 | 详细说明 |
|---|---|---|---|
enable | boolean | false | 全局启用自动类型获取 |
include | string[] | - | 指定需要自动获取类型的库(如 ["jquery", "lodash"]) |
exclude | string[] | - | 指定排除自动获取类型的库 |
2.4 compilerOptions 核心子配置(全量)
2.4.1 目标环境与兼容性
| 配置项 | 类型 | 默认值 | 详细说明 |
|---|---|---|---|
target | string | ES3 | 编译后的 JS 版本(可选:ES5、ES2015/ES6、ES2016~ES2025、ESNext) |
module | string | 随 target 自动适配 | 模块系统(可选:CommonJS、ESNext、ES2020、UMD、AMD、System、ES6、None) |
moduleResolution | string | Node(CommonJS)/Classic(ES6) | 模块解析策略: - Node:模拟 Node.js 模块解析逻辑(推荐) - Classic:TS 早期解析方式 |
lib | string[] | 随 target 自动推断 | 指定编译时依赖的内置库(需手动指定非默认库,如 DOM、ES2020.Promise、WebWorker、DOM.Iterable、ES2022.Error) |
jsx | string | preserve | JSX 处理方式: - preserve:保留 JSX(交给 Babel/React 处理) - react:编译为 React.createElement - react-jsx:编译为 _jsx 函数(React 17+ 推荐) - react-jsxdev:开发环境的 react-jsx |
jsxFactory | string | React.createElement | 自定义 JSX 工厂函数(如 h 用于 Vue/Preact) |
jsxFragmentFactory | string | React.Fragment | 自定义 JSX 片段工厂函数(如 Fragment) |
jsxImportSource | string | - | 指定 JSX 运行时导入源(如 react-jsx、preact) |
experimentalDecorators | boolean | false | 启用装饰器语法(ES 实验特性,如类装饰器、方法装饰器) |
emitDecoratorMetadata | boolean | false | 启用装饰器元数据生成(需配合 experimentalDecorators 使用) |
esModuleInterop | boolean | false | 启用 ES 模块与 CommonJS 互操作(解决 import React from 'react' 兼容性问题) |
allowSyntheticDefaultImports | boolean | false | 允许合成默认导入(如 import React from 'react' 而非 import * as React from 'react') |
forceConsistentCasingInFileNames | boolean | false | 强制文件路径大小写一致(避免跨平台路径错误) |
charset | string | utf8 | 指定源码文件编码格式(如 utf8、gbk、utf16) |
emitBOM | boolean | false | 编译后的文件开头添加 UTF-8 BOM 头 |
useDefineForClassFields | boolean | false | 遵循 ES 标准的类字段定义(public/private 等修饰符行为) |
2.4.2 代码输出控制
| 配置项 | 类型 | 默认值 | 详细说明 |
|---|---|---|---|
outDir | string | - | 指定编译后 JS 文件的输出目录(如 ./dist),未指定则输出到源码同级目录 |
outFile | string | - | 将所有编译后的文件合并为单个 JS 文件(仅支持 AMD/System 模块) |
rootDir | string | 项目根 | 指定源码根目录(确保输出目录结构与源码一致,避免多目录编译时结构混乱) |
rootDirs | string[] | - | 虚拟根目录配置(将多个目录合并为一个虚拟根目录,适用于多源码目录) |
removeComments | boolean | false | 编译后移除所有注释(生产环境推荐开启) |
noEmit | boolean | false | 仅执行类型检查,不生成任何 JS 文件(适用于仅做类型校验的场景) |
noEmitOnError | boolean | false | 编译出错时不生成 JS 文件(生产环境推荐开启) |
sourceMap | boolean | false | 生成 sourceMap 文件(方便调试 TS 源码,开发环境推荐开启) |
inlineSourceMap | boolean | false | 将 sourceMap 内联到 JS 文件中(而非生成单独 .map 文件) |
sourceRoot | string | - | 指定 sourceMap 中源码的根路径(用于调试时定位源码) |
mapRoot | string | - | 指定 sourceMap 文件的根路径(用于调试时加载 map 文件) |
inlineSources | boolean | false | 将源码内联到 sourceMap 中(需配合 sourceMap/inlineSourceMap 使用) |
declaration | boolean | false | 生成 .d.ts 类型声明文件(发布 npm 库时必须开启) |
declarationDir | string | - | 指定 .d.ts 文件的输出目录(未指定则与 outDir 一致) |
declarationMap | boolean | false | 为 .d.ts 文件生成 sourceMap(方便调试类型声明) |
emitDeclarationOnly | boolean | false | 仅生成 .d.ts 文件,不生成 JS 文件(适用于纯类型库开发) |
downlevelIteration | boolean | false | 为低版本 JS 目标启用迭代器兼容(如 ES5 支持 for...of 循环) |
newLine | string | 系统默认 | 指定换行符类型(CRLF/Windows、LF/Unix) |
preserveConstEnums | boolean | false | 保留 const enum 枚举(默认编译后会被内联,开启后保留枚举定义) |
declarationDir | string | - | 类型声明文件输出目录 |
stripInternal | boolean | false | 移除带有 @internal 注解的类型声明(发布库时隐藏内部类型) |
importHelpers | boolean | false | 导入 tslib 辅助函数(如 **extends、**assign),减小编译后代码体积 |
importsNotUsedAsValues | string | remove | 未使用的导入处理策略: - remove:移除 - preserve:保留 - error:报错 |
preserveValueImports | boolean | false | 保留值导入(即使未使用,避免副作用丢失) |
2.4.3 严格类型检查(全量核心)
| 配置项 | 类型 | 默认值 | 详细说明 |
| ------------------------------------ | ------- | ------ | ---------------------------------------------------------------------- | ------- |
| strict | boolean | false | 启用所有严格类型检查选项(推荐开启,等同于下方所有 strict* 为 true) |
| strictNullChecks | boolean | false | 严格空值检查(null/undefined 不能赋值给非空类型,需显式声明 T | null) |
| strictFunctionTypes | boolean | false | 严格函数类型检查(禁止函数参数/返回值的隐式类型兼容,避免类型不安全) |
| strictPropertyInitialization | boolean | false | 严格属性初始化检查(类的属性必须在构造函数/属性初始化器中赋值) |
| strictBindCallApply | boolean | false | 严格绑定函数 this 类型(bind/call/apply 时校验参数类型) |
| strictMath | boolean | false | 严格数学运算检查(禁止 NaN/Infinity 隐式转换) |
| noImplicitAny | boolean | false | 禁止隐式 any 类型(未指定类型的变量/参数必须显式声明 any) |
| noImplicitThis | boolean | false | 禁止隐式 this 类型(this 必须有明确的类型,避免指向全局) |
| alwaysStrict | boolean | false | 编译后的 JS 文件顶部添加 "use strict" 严格模式声明 |
| noUnusedLocals | boolean | false | 禁止未使用的局部变量(编译报错,可通过 // @ts-ignore 临时忽略) |
| noUnusedParameters | boolean | false | 禁止未使用的函数参数(编译报错,可选参数 ? 或剩余参数 ... 不受限) |
| noImplicitReturns | boolean | false | 禁止函数分支未返回值(如 if 有返回,else 无返回则报错) |
| noFallthroughCasesInSwitch | boolean | false | 禁止 switch 语句 case 穿透(未加 break/return/throw 的情况报错) |
| noUncheckedIndexedAccess | boolean | false | 禁止未检查的索引访问(如数组/对象索引访问需校验是否存在) |
| noPropertyAccessFromIndexSignature | boolean | false | 禁止通过点语法访问索引签名属性(强制使用方括号) |
| noImplicitOverride | boolean | false | 禁止未使用 override 关键字重写父类方法 |
| noImplicitReturns | boolean | false | 禁止函数有分支未显式返回值 |
| noStrictGenericChecks | boolean | false | 放宽泛型类型检查(关闭严格泛型匹配) |
| useUnknownInCatchVariables | boolean | false | catch 变量默认类型为 unknown(而非 any,需显式类型断言) |
2.4.4 模块与路径配置
| 配置项 | 类型 | 默认值 | 详细说明 |
|---|---|---|---|
baseUrl | string | - | 模块解析的基础路径(配合 paths 使用,如 ./ 或 ./src) |
paths | object | - | 路径别名配置(需配合 baseUrl),示例:json<br>"paths": {<br> "@/*": ["src/*"],<br> "@/utils/*": ["src/utils/*"]<br>}<br> |
typeRoots | string[] | ["node_modules/@types"] | 指定类型声明文件的查找目录(可自定义添加 src/types 等) |
types | string[] | - | 仅加载指定的类型声明包(如 ["node", "jest", "react"],未指定则加载所有 @types) |
allowUmdGlobalAccess | boolean | false | 允许访问 UMD 模块的全局变量(如直接使用 jQuery 而非 import) |
moduleSuffixes | string[] | - | 模块解析后缀(如 ["", ".ts", ".tsx"],优先匹配靠前的后缀) |
resolveJsonModule | boolean | false | 允许导入 JSON 文件(如 import config from './config.json') |
allowImportingTsExtensions | boolean | false | 允许导入时保留 .ts/.tsx 后缀(如 import foo from './foo.ts') |
resolvePackageJsonExports | boolean | true | 解析 package.json 的 exports 字段(遵循 Node.js 模块解析规则) |
resolvePackageJsonImports | boolean | true | 解析 package.json 的 imports 字段(私有路径映射) |
customConditions | string[] | - | 自定义解析条件(配合 package.json 的 exports/imports 字段) |
allowArbitraryExtensions | boolean | false | 允许导入任意扩展名的文件(需配合自定义解析器) |
2.4.5 语法与兼容性配置
| 配置项 | 类型 | 默认值 | 详细说明 |
|---|---|---|---|
allowJs | boolean | false | 允许编译 JS 文件(适用于 TS/JS 混合项目) |
checkJs | boolean | false | 检查 JS 文件的类型错误(需配合 allowJs 使用) |
maxNodeModuleJsDepth | number | 0 | 检查 node_modules 中 JS 文件的深度(0 表示不检查) |
isolatedModules | boolean | false | 强制每个文件为独立模块(避免全局变量污染,适配 Babel/ESBuild 等工具) |
moduleDetection | string | auto | 模块检测策略: - auto:自动检测 - force:强制所有文件为模块 - legacy:旧版检测逻辑 |
experimentalDecorators | boolean | false | 启用装饰器(同前文,补充:TS 5.0+ 支持装饰器标准语法) |
decoratorMetadata | boolean | false | 装饰器元数据(同 emitDecoratorMetadata,别名) |
suppressExcessPropertyErrors | boolean | false | 抑制对象字面量多余属性错误(如 {a:1, b:2} 赋值给 {a: number}) |
suppressImplicitAnyIndexErrors | boolean | false | 抑制隐式 any 索引错误(如 obj[key] 中 key 为任意字符串) |
2.4.6 错误与警告控制
| 配置项 | 类型 | 默认值 | 详细说明 |
|---|---|---|---|
skipLibCheck | boolean | false | 跳过第三方库(node_modules)的类型检查(提升编译速度,避免库类型错误) |
allowUnreachableCode | boolean | true | 允许不可达代码(关闭则编译报错,如 return 后的代码) |
allowUnusedLabels | boolean | true | 允许未使用的标签(关闭则编译报错,如循环标签) |
noErrorTruncation | boolean | false | 不截断错误信息(显示完整的类型错误详情) |
preserveWatchOutput | boolean | false | 监听模式下保留之前的输出(不清空控制台) |
disableSizeLimit | boolean | false | 禁用编译器大小限制(适用于超大项目) |
noLib | boolean | false | 不包含默认的库文件(如 lib.d.ts) |
disableReferencedProjectLoad | boolean | false | 禁用引用项目的加载(提升编译速度) |
disableSolutionSearching | boolean | false | 禁用解决方案搜索(Monorepo 项目优化) |
disableSourceOfProjectReferenceRedirect | boolean | false | 禁用项目引用重定向的源映射 |
2.4.7 高级编译配置
| 配置项 | 类型 | 默认值 | 详细说明 |
|---|---|---|---|
composite | boolean | false | 启用复合项目(Monorepo 必备,生成 .tsbuildinfo 文件实现增量编译) |
tsBuildInfoFile | string | - | 指定 .tsbuildinfo 增量编译缓存文件路径 |
disableIncremental | boolean | false | 禁用增量编译(强制全量编译) |
preserveSymlinks | boolean | false | 保留符号链接(解析模块时使用符号链接路径而非真实路径) |
traceResolution | boolean | false | 输出模块解析过程(调试路径别名/模块找不到问题) |
listFiles | boolean | false | 列出编译器处理的所有文件(调试编译范围问题) |
listEmittedFiles | boolean | false | 列出编译后输出的所有文件 |
listDerivedFiles | boolean | false | 列出衍生的文件(如 .d.ts、.map 文件) |
diagnostics | boolean | false | 输出编译器诊断信息(性能、耗时等) |
extendedDiagnostics | boolean | false | 输出扩展诊断信息(更详细的编译统计) |
explainFiles | boolean | false | 解释文件被包含/排除的原因(调试 include/exclude 问题) |
generateCpuProfile | string | - | 生成 CPU 性能分析文件(路径如 ./tsc-profile.cpuprofile) |
disableCompilerHost | boolean | false | 禁用编译器宿主(自定义编译流程时使用) |
三、场景化配置示例
3.1 Node.js 后端项目(Node 20+ 全功能版)
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"moduleResolution": "Node",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"sourceMap": true,
"declaration": true,
"declarationDir": "./dist/types",
"resolveJsonModule": true,
"baseUrl": "./",
"paths": {
"@/*": ["src/*"],
"@/config/*": ["src/config/*"],
"@/services/*": ["src/services/*"]
},
"typeRoots": ["node_modules/@types", "src/types"],
"types": ["node", "jest"],
"noUncheckedIndexedAccess": true,
"useUnknownInCatchVariables": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"incremental": true,
"tsBuildInfoFile": "./.tsbuildinfo"
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist", "**/*.test.ts"],
"watchOptions": {
"watchFile": "useFsEvents",
"excludeDirectories": ["node_modules", "dist"]
}
}