1. 核心配置项
compilerOptions
compilerOptions 是 tsconfig.json 中最重要的部分,用于配置 TypeScript 编译器的行为。以下是一些常用选项:
| 配置项 | 说明 |
|---|---|
target | 指定编译后的 JavaScript 目标版本(如 ES5、ES6、ES2020)。 |
module | 指定模块系统(如 CommonJS、ES6、UMD)。 |
outDir | 指定编译后的输出目录(如 ./dist)。 |
rootDir | 指定源文件的根目录(如 ./src)。 |
strict | 启用所有严格类型检查选项(推荐启用)。 |
noImplicitAny | 禁止隐式的 any 类型(启用 strict 时默认开启)。 |
strictNullChecks | 启用严格的 null 和 undefined 检查(启用 strict 时默认开启)。 |
esModuleInterop | 允许 CommonJS 模块与 ES 模块的互操作(推荐启用)。 |
skipLibCheck | 跳过库文件的类型检查(可加快编译速度)。 |
allowJs | 允许编译 JavaScript 文件。 |
checkJs | 对 JavaScript 文件进行类型检查(需启用 allowJs)。 |
sourceMap | 生成 .map 文件,用于调试。 |
declaration | 生成 .d.ts 类型声明文件。 |
removeComments | 移除注释。 |
noEmitOnError | 如果编译出错,不生成输出文件。 |
jsx | 指定 JSX 的处理方式(如 preserve、react、react-jsx)。 |
lib | 指定包含的库文件(如 ["ES6", "DOM"])。 |
baseUrl | 解析非相对模块的基础路径。 |
paths | 配置模块路径映射(需与 baseUrl 配合使用)。 |
typeRoots | 指定类型声明文件的查找路径。 |
types | 指定包含的类型声明文件包。 |
allowSyntheticDefaultImports | 允许从没有默认导出的模块中默认导入(推荐启用)。 |
resolveJsonModule | 允许导入 JSON 文件。 |
示例
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"sourceMap": true
}
}
2. 文件包含与排除
include
指定需要编译的文件或目录(支持 glob 模式)。例如:
{
"include": ["src/**/*"]
}
exclude
指定需要排除的文件或目录(支持 glob 模式)。例如:
{
"exclude": ["node_modules", "**/*.test.ts"]
}
files
显式指定需要编译的文件列表。例如:
{
"files": ["src/index.ts", "src/utils.ts"]
}
3. 扩展配置
extends
继承其他配置文件。例如:
json
复制
{
"extends": "./base-config.json"
}
4. 其他配置
references
用于配置项目引用(Project References),支持将大型项目拆分为多个子项目。例如:
{
"references": [
{ "path": "./shared" },
{ "path": "./app" }
]
}
compileOnSave
指定是否在保存文件时自动编译(通常由编辑器支持)。例如:
{
"compileOnSave": true
}
5. 完整示例
以下是一个完整的 tsconfig.json 示例:
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"sourceMap": true,
"declaration": true,
"allowJs": true,
"checkJs": true,
"baseUrl": ".",
"paths": {
"@utils/*": ["src/utils/*"]
}
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.test.ts"]
}
6. 常用配置组合
Node.js 项目
{
"compilerOptions": {
"target": "ES6",
"module": "CommonJS",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}
前端项目(React + TypeScript)
{
"compilerOptions": {
"target": "ES6",
"module": "ES6",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"jsx": "react-jsx",
"sourceMap": true
},
"include": ["src/**/*"]
}