tsconfig.json 配置文件,用于指定编译选项和文件包含规则

87 阅读2分钟

1. 核心配置项

compilerOptions

compilerOptions 是 tsconfig.json 中最重要的部分,用于配置 TypeScript 编译器的行为。以下是一些常用选项:

配置项说明
target指定编译后的 JavaScript 目标版本(如 ES5ES6ES2020)。
module指定模块系统(如 CommonJSES6UMD)。
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 的处理方式(如 preservereactreact-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/**/*"]
}