📁 创建 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"] // 排除的文件
}
🔒 严格模式选项
{
"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"]
}