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
}
}
相关阅读
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。
「frontend」更多文章
Vue 性能优化指南:虚拟列表、懒加载、渲染优化与 Core Web Vitals
Vue 3 应用性能优化完整策略:虚拟滚动(vue-virtual-scroller)、组件懒加载与异步组件、KeepAlive 缓存、Suspense 异步优化、v-memo 渲染记忆化、响应式性能(shallowRef/toRaw)、Bundle 分析与代码分割、渲染函数优化、以及 Core Web Vitals(LCP/INP/CLS)调优。
Nuxt.js 完全指南:Vue 全栈框架的 SSR、SSG、API 路由与部署实践
Nuxt.js 3 深度实践:文件系统路由、SSR/SSG/ISR 渲染模式、API 路由(Server Routes)、useFetch/useAsyncData 数据获取、中间件与插件、SEO 与 Meta 管理、Nitro 服务端引擎、自动导入、部署到 Vercel/Netlify/Node.js。
Vue 测试深度指南:Vitest + Vue Test Utils + Playwright E2E 与 CI 集成
Vue 3 应用从单元测试到 E2E 的完整测试策略:Vitest + Vue Test Utils 组件测试(mount/emits/slots/async)、Pinia Store Mocking、MSW API 拦截、Playwright 端到端测试、Cypress 组件测试、覆盖率标准与 GitHub Actions CI 集成。