TypeScript tsconfig.json

tsconfig.json 是 TypeScript 项目的配置文件,位于项目根目录,告诉编译器:编译哪些文件、输出到哪里、采用什么编译选项。只要存在该文件,直接运行 tsc 即可按配置编译整个项目。

配置文件的作用

  • 充当项目根目录标记:tsc 会向上查找最近的 tsconfig.json。
  • 集中管理编译选项,取代一长串命令行参数。
  • 指定参与编译的文件范围(include/exclude)。

生成默认配置

执行以下命令可自动生成一份带完整注释的 tsconfig.json:

tsc --init

生成后无需修改即可编译当前目录下的 .ts 文件。

最小示例

一个最简单的 tsconfig.json 只需 compilerOptions:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "strict": true,
    "outDir": "./dist",
    "rootDir": "./src"
  }
}

此时运行 tsc,会把 src 下的 .ts 编译到 dist 目录。

常用配置项

配置项作用示例值
target编译为哪个 ES 版本ES5、ES2020、ESNext
module模块系统commonjs、esnext、amd
outDir输出目录./dist
rootDir源文件根目录./src
strict开启全部严格检查true
sourceMap生成 .map 调试文件true
declaration生成 .d.ts 声明文件true
removeComments编译结果去除注释true

include 与 exclude

用 glob 通配符控制编译范围:

{
  "compilerOptions": { "outDir": "./dist" },
  "include": ["src/**/*", "tests/**/*.ts"],
  "exclude": ["node_modules", "dist", "**/*.spec.ts"]
}
  • include:参与编译的文件(默认含当前目录全部 .ts)。
  • exclude:排除的文件,优先级高于 include。

多文件配置继承 extends

大型项目拆分为多个子项目时,可让子配置继承公共配置:

// tsconfig.base.json —— 公共基础
{
  "compilerOptions": { "strict": true, "target": "ES2020" }
}
// 子项目 tsconfig.json —— 继承并覆盖
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": { "outDir": "./dist" }
}

验证配置

编译时可用 --showConfig 查看最终生效的完整配置:

tsc --showConfig

小结

tsconfig.json 是 TS 工程的"总开关":一条 tsc 命令即可完成全部编译。掌握 compilerOptions、include/exclude 与 extends 三块内容,就能驾驭任意规模的 TypeScript 项目;下一节再逐个细看编译选项的用法。

笔记加载中…