TypeScript 配置文件 (tsconfig.json) 终极指南

一、配置文件核心意义

tsconfig.json 是 TypeScript 项目的核心配置文件,用于定义 TypeScript 编译器(tsc)的编译规则、类型检查策略、输出行为等。当在项目根目录执行 tsc 命令时,编译器会自动读取该文件并应用配置;若未指定 tsconfig.json,编译器将使用默认规则。

二、完整配置项详解(无遗漏版)

2.1 顶层基础配置

配置项类型默认值详细说明
compilerOptionsobject-编译器核心配置(所有编译相关规则均在此节点下)
includestring[]["**/*"]指定需要编译的文件/目录,支持 glob 通配符(如 src/**/*.tssrc/**/*.tsx
excludestring[]["node_modules", "bower_components", "jspm_packages"]指定排除编译的文件/目录,优先级高于 include,可自定义添加 distbuild
filesstring[]-显式指定需要编译的单个文件列表(优先级最高,适用于少量文件的项目)
extendsstring-继承外部 tsconfig 配置(支持相对路径或 npm 包,如 @tsconfig/node20/tsconfig.json
referencesobject[]-项目引用配置,用于 Monorepo 多项目依赖场景,实现增量编译和类型隔离
typeAcquisitionobject{ "enable": false, "include": [], "exclude": [] }自动类型获取配置(针对未安装 @types 的第三方库)
compileOnSavebooleanfalse编辑器保存时自动编译(需编辑器支持,如 VS Code)
watchOptionsobject-监听模式(tsc --watch)的配置项,控制文件监听行为

2.2 watchOptions 子配置(监听模式)

配置项类型默认值详细说明
watchFilestringuseFsEvents文件监听方式:
- useFsEvents:使用系统文件监听(推荐)
- useFsEventsOnParentDirectory:监听父目录
- fixedPollingInterval:固定轮询
- priorityPollingInterval:优先级轮询
watchDirectorystringuseFsEvents目录监听方式(同 watchFile 取值)
fallbackPollingstringfixedPollingInterval监听降级策略(文件监听失败时使用)
synchronousWatchDirectorybooleanfalse同步监听目录变化(避免竞态条件)
excludeDirectoriesstring[]-排除监听的目录(如 ["node_modules", "dist"]
excludeFilesstring[]-排除监听的文件(如 ["**/*.log", "**/*.tmp"]

2.3 typeAcquisition 子配置(自动类型获取)

配置项类型默认值详细说明
enablebooleanfalse全局启用自动类型获取
includestring[]-指定需要自动获取类型的库(如 ["jquery", "lodash"]
excludestring[]-指定排除自动获取类型的库

2.4 compilerOptions 核心子配置(全量)

2.4.1 目标环境与兼容性

配置项类型默认值详细说明
targetstringES3编译后的 JS 版本(可选:ES5、ES2015/ES6、ES2016~ES2025、ESNext)
modulestring随 target 自动适配模块系统(可选:CommonJS、ESNext、ES2020、UMD、AMD、System、ES6、None)
moduleResolutionstringNode(CommonJS)/Classic(ES6)模块解析策略:
- Node:模拟 Node.js 模块解析逻辑(推荐)
- Classic:TS 早期解析方式
libstring[]随 target 自动推断指定编译时依赖的内置库(需手动指定非默认库,如 DOM、ES2020.Promise、WebWorker、DOM.Iterable、ES2022.Error)
jsxstringpreserveJSX 处理方式:
- preserve:保留 JSX(交给 Babel/React 处理)
- react:编译为 React.createElement
- react-jsx:编译为 _jsx 函数(React 17+ 推荐)
- react-jsxdev:开发环境的 react-jsx
jsxFactorystringReact.createElement自定义 JSX 工厂函数(如 h 用于 Vue/Preact)
jsxFragmentFactorystringReact.Fragment自定义 JSX 片段工厂函数(如 Fragment
jsxImportSourcestring-指定 JSX 运行时导入源(如 react-jsxpreact
experimentalDecoratorsbooleanfalse启用装饰器语法(ES 实验特性,如类装饰器、方法装饰器)
emitDecoratorMetadatabooleanfalse启用装饰器元数据生成(需配合 experimentalDecorators 使用)
esModuleInteropbooleanfalse启用 ES 模块与 CommonJS 互操作(解决 import React from 'react' 兼容性问题)
allowSyntheticDefaultImportsbooleanfalse允许合成默认导入(如 import React from 'react' 而非 import * as React from 'react'
forceConsistentCasingInFileNamesbooleanfalse强制文件路径大小写一致(避免跨平台路径错误)
charsetstringutf8指定源码文件编码格式(如 utf8、gbk、utf16)
emitBOMbooleanfalse编译后的文件开头添加 UTF-8 BOM 头
useDefineForClassFieldsbooleanfalse遵循 ES 标准的类字段定义(public/private 等修饰符行为)

2.4.2 代码输出控制

配置项类型默认值详细说明
outDirstring-指定编译后 JS 文件的输出目录(如 ./dist),未指定则输出到源码同级目录
outFilestring-将所有编译后的文件合并为单个 JS 文件(仅支持 AMD/System 模块)
rootDirstring项目根指定源码根目录(确保输出目录结构与源码一致,避免多目录编译时结构混乱)
rootDirsstring[]-虚拟根目录配置(将多个目录合并为一个虚拟根目录,适用于多源码目录)
removeCommentsbooleanfalse编译后移除所有注释(生产环境推荐开启)
noEmitbooleanfalse仅执行类型检查,不生成任何 JS 文件(适用于仅做类型校验的场景)
noEmitOnErrorbooleanfalse编译出错时不生成 JS 文件(生产环境推荐开启)
sourceMapbooleanfalse生成 sourceMap 文件(方便调试 TS 源码,开发环境推荐开启)
inlineSourceMapbooleanfalse将 sourceMap 内联到 JS 文件中(而非生成单独 .map 文件)
sourceRootstring-指定 sourceMap 中源码的根路径(用于调试时定位源码)
mapRootstring-指定 sourceMap 文件的根路径(用于调试时加载 map 文件)
inlineSourcesbooleanfalse将源码内联到 sourceMap 中(需配合 sourceMap/inlineSourceMap 使用)
declarationbooleanfalse生成 .d.ts 类型声明文件(发布 npm 库时必须开启)
declarationDirstring-指定 .d.ts 文件的输出目录(未指定则与 outDir 一致)
declarationMapbooleanfalse为 .d.ts 文件生成 sourceMap(方便调试类型声明)
emitDeclarationOnlybooleanfalse仅生成 .d.ts 文件,不生成 JS 文件(适用于纯类型库开发)
downlevelIterationbooleanfalse为低版本 JS 目标启用迭代器兼容(如 ES5 支持 for...of 循环)
newLinestring系统默认指定换行符类型(CRLF/Windows、LF/Unix)
preserveConstEnumsbooleanfalse保留 const enum 枚举(默认编译后会被内联,开启后保留枚举定义)
declarationDirstring-类型声明文件输出目录
stripInternalbooleanfalse移除带有 @internal 注解的类型声明(发布库时隐藏内部类型)
importHelpersbooleanfalse导入 tslib 辅助函数(如 **extends、**assign),减小编译后代码体积
importsNotUsedAsValuesstringremove未使用的导入处理策略:
- remove:移除
- preserve:保留
- error:报错
preserveValueImportsbooleanfalse保留值导入(即使未使用,避免副作用丢失)

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 模块与路径配置

配置项类型默认值详细说明
baseUrlstring-模块解析的基础路径(配合 paths 使用,如 ././src
pathsobject-路径别名配置(需配合 baseUrl),示例:
json<br>"paths": {<br> "@/*": ["src/*"],<br> "@/utils/*": ["src/utils/*"]<br>}<br>
typeRootsstring[]["node_modules/@types"]指定类型声明文件的查找目录(可自定义添加 src/types 等)
typesstring[]-仅加载指定的类型声明包(如 ["node", "jest", "react"],未指定则加载所有 @types)
allowUmdGlobalAccessbooleanfalse允许访问 UMD 模块的全局变量(如直接使用 jQuery 而非 import)
moduleSuffixesstring[]-模块解析后缀(如 ["", ".ts", ".tsx"],优先匹配靠前的后缀)
resolveJsonModulebooleanfalse允许导入 JSON 文件(如 import config from './config.json'
allowImportingTsExtensionsbooleanfalse允许导入时保留 .ts/.tsx 后缀(如 import foo from './foo.ts'
resolvePackageJsonExportsbooleantrue解析 package.json 的 exports 字段(遵循 Node.js 模块解析规则)
resolvePackageJsonImportsbooleantrue解析 package.json 的 imports 字段(私有路径映射)
customConditionsstring[]-自定义解析条件(配合 package.json 的 exports/imports 字段)
allowArbitraryExtensionsbooleanfalse允许导入任意扩展名的文件(需配合自定义解析器)

2.4.5 语法与兼容性配置

配置项类型默认值详细说明
allowJsbooleanfalse允许编译 JS 文件(适用于 TS/JS 混合项目)
checkJsbooleanfalse检查 JS 文件的类型错误(需配合 allowJs 使用)
maxNodeModuleJsDepthnumber0检查 node_modules 中 JS 文件的深度(0 表示不检查)
isolatedModulesbooleanfalse强制每个文件为独立模块(避免全局变量污染,适配 Babel/ESBuild 等工具)
moduleDetectionstringauto模块检测策略:
- auto:自动检测
- force:强制所有文件为模块
- legacy:旧版检测逻辑
experimentalDecoratorsbooleanfalse启用装饰器(同前文,补充:TS 5.0+ 支持装饰器标准语法)
decoratorMetadatabooleanfalse装饰器元数据(同 emitDecoratorMetadata,别名)
suppressExcessPropertyErrorsbooleanfalse抑制对象字面量多余属性错误(如 {a:1, b:2} 赋值给 {a: number})
suppressImplicitAnyIndexErrorsbooleanfalse抑制隐式 any 索引错误(如 obj[key] 中 key 为任意字符串)

2.4.6 错误与警告控制

配置项类型默认值详细说明
skipLibCheckbooleanfalse跳过第三方库(node_modules)的类型检查(提升编译速度,避免库类型错误)
allowUnreachableCodebooleantrue允许不可达代码(关闭则编译报错,如 return 后的代码)
allowUnusedLabelsbooleantrue允许未使用的标签(关闭则编译报错,如循环标签)
noErrorTruncationbooleanfalse不截断错误信息(显示完整的类型错误详情)
preserveWatchOutputbooleanfalse监听模式下保留之前的输出(不清空控制台)
disableSizeLimitbooleanfalse禁用编译器大小限制(适用于超大项目)
noLibbooleanfalse不包含默认的库文件(如 lib.d.ts)
disableReferencedProjectLoadbooleanfalse禁用引用项目的加载(提升编译速度)
disableSolutionSearchingbooleanfalse禁用解决方案搜索(Monorepo 项目优化)
disableSourceOfProjectReferenceRedirectbooleanfalse禁用项目引用重定向的源映射

2.4.7 高级编译配置

配置项类型默认值详细说明
compositebooleanfalse启用复合项目(Monorepo 必备,生成 .tsbuildinfo 文件实现增量编译)
tsBuildInfoFilestring-指定 .tsbuildinfo 增量编译缓存文件路径
disableIncrementalbooleanfalse禁用增量编译(强制全量编译)
preserveSymlinksbooleanfalse保留符号链接(解析模块时使用符号链接路径而非真实路径)
traceResolutionbooleanfalse输出模块解析过程(调试路径别名/模块找不到问题)
listFilesbooleanfalse列出编译器处理的所有文件(调试编译范围问题)
listEmittedFilesbooleanfalse列出编译后输出的所有文件
listDerivedFilesbooleanfalse列出衍生的文件(如 .d.ts、.map 文件)
diagnosticsbooleanfalse输出编译器诊断信息(性能、耗时等)
extendedDiagnosticsbooleanfalse输出扩展诊断信息(更详细的编译统计)
explainFilesbooleanfalse解释文件被包含/排除的原因(调试 include/exclude 问题)
generateCpuProfilestring-生成 CPU 性能分析文件(路径如 ./tsc-profile.cpuprofile
disableCompilerHostbooleanfalse禁用编译器宿主(自定义编译流程时使用)

三、场景化配置示例

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"]
  }
}

四下皆无人