模块与配置
tsconfig.json 详解
掌握 strict、target、moduleResolution、paths 等核心配置
tsconfig.json 详解
tsconfig.json 控制 TypeScript 编译器行为,正确配置至关重要。
学完本章你将: 掌握 strict、target、module 等核心配置。
基本结构
json
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
核心配置详解
typescript
// target —— 编译目标 JS 版本
// "ES5" | "ES6" | "ES2022" | "ESNext"
// module —— 模块系统
// "CommonJS" | "ESNext" | "Node16" | "Preserve"
// strict —— 开启所有严格检查(推荐 true)
// 包含:strictNullChecks、noImplicitAny 等
// esModuleInterop —— 允许 import * as X from 'cjs'
// skipLibCheck —— 跳过 .d.ts 检查(加速编译)
// declaration —— 生成 .d.ts 文件
// sourceMap —— 生成 source map
路径与输出
json
{
"compilerOptions": {
"outDir": "dist", // 输出目录
"rootDir": "src", // 源码目录
"baseUrl": ".", // 路径基准
"paths": { // 路径别名
"@/*": ["src/*"],
"@lib/*": ["src/lib/*"]
}
}
}
项目引用
json
// root tsconfig.json
{
"files": [],
"references": [
{ "path": "./packages/core" },
{ "path": "./packages/web" }
]
}
// packages/core/tsconfig.json
{
"compilerOptions": {
"composite": true, // 必须启用
"outDir": "./dist"
}
}
编译:tsc --build