tsconfig.JSON 配置
配置 TypeScript 编译器使用 tsconfig.JSON: 目标, strict, paths, and 更多.
你将学到
- 必要 tsconfig.JSON options: 目标, 模块, and lib
- 如何 strict 模式启用 bundle 的 safety 检查
- Path aliases 使用 baseUrl and paths for cleaner 导入
- 项目引用 and composite 项目 for monorepos
概念讲解
Core Options
The tsconfig.JSON file configures the TypeScript compiler. The most important options are 目标 (the JavaScript version to compile to, e.g. es2020), 模块 (the module system, e.g. esnext or commonjs), and lib (which built-in APIs are available, e.g. ["es2020", "DOM"]). outDir specifies where compiled JavaScript goes, and rootDir specifies where source files live.
Strict Mode
The strict: 真 flag enables a bundle of safety checks: strictNullChecks (null/undefined are not assignable to other types), noImplicitAny (parameters must have types or be inferable), strictFunctionTypes, strictBindCallApply, strictPropertyInitialization, noImplicitThis, and alwaysStrict. Enabling strict is the single best decision for a new TypeScript project — it catches the most bugs with the least effort.
Path Aliases and References
Path aliases (paths) let you import with absolute paths instead of long relative ones: 导入 { 用户 } 从 "@models/用户" instead of ../../../models/用户. You configure them with baseUrl and paths in tsconfig. Project references (引用 with composite: 真) let you split a large project into smaller sub-projects that compile independently, which is essential for monorepo performance.
示例代码
// tsconfig.json — a modern, strict configuration.
{
"compilerOptions": {
"target": "es2020",
"module": "esnext",
"moduleResolution": "bundler",
"lib": ["es2020", "dom"],
// Strict mode — enables all safety checks.
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
// Output.
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"sourceMap": true,
// Path aliases for clean imports.
"baseUrl": "./src",
"paths": {
"@models/*": ["models/*"],
"@utils/*": ["utils/*"],
"@components/*": ["components/*"]
},
// Module resolution.
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
tsconfig.JSON controls 编译器. 目标设置 JS version, strict 启用 safety 检查, paths 创建导入 aliases. 总是启用 strict for 新项目 — 它 catches 大多数 bugs.
动手试一试
- Code Minifier
目标设置 determines 哪个 JS features 获取 transpiled 下.
- Code Diff
Compare compiled 输出跨越不同目标设置.
常见错误
错误写法
禁用 strictNullChecks or strict 到 avoid fixing 类型错误
正确做法
Keep strict 启用. 错误它 surfaces 是真实 bugs. Fix code 而不是 weakening 编译器. 短-term pain prevents 长-term 运行时错误.
错误写法
设置目标也 低 and losing modern JavaScript features
正确做法
设置目标到 match 你的运行时环境 (es2020 for modern 浏览器/节点). 也-低目标 transpiles features unnecessarily, producing larger and slower 输出.
练习 tsconfig.JSON 配置
1 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。