tsconfig.json 是 TypeScript 项目的核心配置文件,合理的配置直接决定了类型检查的严格程度和编译输出的质量。本文逐项拆解关键配置,给出不同场景下的推荐配置模板。
一、strict 全家桶详解
| 配置项 | 作用 | 建议 |
|---|---|---|
strict | 总开关,启用全部严格选项 | ✅ 新项目一律开启 |
noImplicitAny | 禁止表达式/声明隐式为 any | ✅ 开启 |
strictNullChecks | null/undefined 需显式处理 | ✅ 开启 |
strictFunctionTypes | 函数参数严格逆变检查 | ✅ 开启 |
strictBindCallApply | bind/call/apply 严格检查 | ✅ 开启 |
strictPropertyInitialization | 类属性必须初始化 | ✅ 开启 |
noImplicitThis | this 类型必须显式 | ✅ 开启 |
alwaysStrict | 严格模式编译 | ✅ 开启 |
二、模块系统选择
| 场景 | target | module | moduleResolution |
|---|---|---|---|
| Node.js 后端 | ES2022 | CommonJS | node |
| Node.js ESM | ES2022 | NodeNext | NodeNext |
| 前端(Vite) | ES2022 | ESNext | bundler |
| 前端(Webpack) | ES2020 | ESNext | node |
| 库(npm 发布) | ES2020 | CommonJS + ESM | node |
三、路径别名配置
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"],
"@utils/*": ["src/utils/*"]
}
}
}
需要配合构建工具(Vite/Webpack)的 resolve.alias。
四、推荐配置模板
前端项目(Vite + React)
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
Node.js 后端
{
"compilerOptions": {
"target": "ES2022",
"module": "CommonJS",
"moduleResolution": "node",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"declaration": true
}
}
相关阅读
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。