tsconfig.json
是 TypeScript 编译器的配置文件,用于告诉编译器如何编译 TypeScript 代码,并控制编译过程中的行为。它可以帮助开发者正确地配置 TypeScript 编译器,以便生成符合预期的 JavaScript 代码。
tsconfig.json
中有很多选项,包括编译目标版本、模块系统类型、库文件、源代码和声明文件的位置等,也可以通过 include
和 exclude
属性来控制编译器要处理哪些文件或目录。
使用 tsconfig.json
可以帮助统一团队内的开发环境和规范,提高代码质量和可维护性。它也是 Angular 等大型项目必不可少的一部分。
tsconfig.json
-
compileOnSave
:boolean
指定编辑器保存文件时是否自动编译,默认为
null
,即继承全局设置。 -
extends
:string
指定要扩展的另一个配置文件(可以是相对路径或绝对路径),当前配置文件将继承该文件的所有选项。
-
include
:string[]
指定要包含在编译中的文件或目录的 glob 模式列表,默认为
["**/*"]
,表示包括所有文件。 -
exclude
:string[]
指定要排除在编译之外的文件或目录的 glob 模式列表,默认为
["node_modules", "bower_components", "jspm_packages"]
。 -
references
:{ path: string }[]
指定项目的引用关系,允许子项目与父项目共享声明文件。
-
files
:string[]
指定要包含在编译中的文件列表,不支持 glob 模式。
-
include
:string[]
指定额外的文件和目录,需要手动添加到编译中,不支持 glob 模式。
-
excludeFiles
:string[]
指定要排除在编译之外的文件列表,不支持 glob 模式。
CompilerOptions
语言特性
target
:"es5"
- 指定编译后的 ECMAScript 目标版本。module
:"commonjs"
- 指定生成的模块类型。lib
:{ "es6": true }
- 指定可用库文件列表。jsx
:"react"
- 指定 JSX 语法支持。declaration
:true
- 是否生成 .d.ts 声明文件。
代码检查
strict
:true
- 启用所有严格类型检查选项。noImplicitAny
:true
- 禁止隐式 any 类型。strictNullChecks
:true
- 使用严格的 null 检查模式。noUnusedLocals
和noUnusedParameters
:true
- 禁止未使用的局部变量和参数。forceConsistentCasingInFileNames
:true
- 强制文件名大小写一致。
模块解析
baseUrl
:"."
- 基本路径,用于解析非相对的导入。paths
:{ "@/*": ["src/*"] }
- 别名映射。rootDirs
:["src", "dist"]
- 允许多个根目录存在。typeRoots
:["node_modules/@types"]
- 用于搜索声明文件的目录。
输出
outDir
:"dist"
- 输出路径。allowJs
:false
- 不允许编译 JavaScript 文件。downlevelIteration
:false
- 不将迭代器降级为 ECMAScript 3 兼容的代码。sourceMap
:true
- 生成 source map 文件。removeComments
:false
- 不删除注释。emitDecoratorMetadata
:true
- 在装饰器元数据中发出。
实验性选项
experimentalDecorators
:true
- 启用实验性的装饰器语法。importHelpers
:true
- 在每个文件中导入辅助函数以减少重复代码。esModuleInterop
:true
- 启用 ES 模块间互操作性。
实例
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"lib": ["es6", "dom"],
"outDir": "dist",
"declaration": true,
"sourceMap": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"esModuleInterop": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
此配置使用 TypeScript 编译器将 src
目录下的所有 .ts
和 .tsx
文件编译成 ES5
标准的 CommonJS
模块,并在 dist
目录生成对应的 .js
和 .d.ts
文件。同时开启了严格类型检查、严格 null 检查等选项,并禁止隐式 any 类型。还使用了 ESLint
进行代码风格检查。