🎯 学习目标

  • 理解 tsconfig.json 的作用和结构
  • 掌握常用编译选项配置
  • 学会配置文件包含和排除规则
  • 了解严格模式配置

📁 创建 tsconfig.json

# 自动生成配置文件 tsc --init # 生成带有注释的配置文件 tsc --init --pretty

生成的默认配置文件包含常用选项的注释说明。

⚙️ 基础配置示例

{ "compilerOptions": { /* 基础选项 */ "target": "ES2020", // 编译目标 ES 版本 "module": "commonjs", // 模块系统 "outDir": "./dist", // 输出目录 "rootDir": "./src", // 源码目录 "strict": true, // 开启严格模式 /* 类型检查 */ "noImplicitAny": true, // 禁止隐式 any "strictNullChecks": true, // 严格的 null 检查 /* 其他选项 */ "esModuleInterop": true, // ES 模块互操作性 "skipLibCheck": true, // 跳过库文件检查 "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], // 包含的文件 "exclude": ["node_modules"] // 排除的文件 }

📊 核心编译选项

选项 说明 常用值
target 编译目标 ES 版本 ES5, ES2015, ES2020, ESNext
module 模块系统 commonjs, es6, esnext, umd
outDir 输出目录 ./dist, ./build
rootDir 源码根目录 ./src
strict 开启所有严格选项 true, false
esModuleInterop ES 模块互操作 true
sourceMap 生成 source map true, false
declaration 生成 .d.ts 声明文件 true, false

🔒 严格模式选项

{ "compilerOptions": { "strict": true, // 开启所有严格检查(推荐) // 以下选项会被 strict 自动启用,也可单独配置 "noImplicitAny": true, // 禁止隐式 any 类型 "strictNullChecks": true, // 严格的 null 检查 "strictFunctionTypes": true, // 严格的函数类型检查 "strictBindCallApply": true, // 严格的 bind/call/apply "strictPropertyInitialization": true, // 严格的类属性初始化 "noImplicitThis": true, // 禁止 this 隐式 any "alwaysStrict": true, // 总是使用严格模式 } }
⚠️
严格模式建议

新项目建议直接开启 strict: true,避免后期迁移困难。现有项目可以逐步开启各项严格检查。

📂 文件包含规则

{ // 包含的文件(使用 glob 模式) "include": [ "src/**/*", // src 目录下所有文件 "tests/**/*.ts" // tests 目录下所有 ts 文件 ], // 排除的文件 "exclude": [ "node_modules", // 排除 node_modules "dist", // 排除输出目录 "**/*.spec.ts" // 排除测试文件 ], // 明确指定的文件(优先级最高) "files": [ "src/main.ts", "src/app.ts" ] }

🔧 实战配置模板

Node.js 项目配置

{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "lib": ["ES2020"], "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "declaration": true, "declarationMap": true, "sourceMap": true }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] }

📝 本节小结

  • • tsconfig.json 是 TypeScript 项目的核心配置文件
  • • 使用 tsc --init 快速生成默认配置
  • • 新项目建议开启 strict 严格模式
  • • 合理配置 include/exclude 管理编译范围