tsconfig.json文件有什么用?
参考答案
作用
tsconfig.json 是 TS 项目的编译配置文件,告诉 tsc 与编辑器:
- 编译哪些文件(
include/exclude/files); - 输出什么(
target/module/outDir/declaration/sourceMap); - 类型检查强度(
strict系列); - 模块解析方式(
moduleResolution/baseUrl/paths); - 与其他工具的协作(
jsx、types、esModuleInterop)。
常用配置示例
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "Bundler",
"strict": true,
"jsx": "react-jsx",
"outDir": "dist",
"rootDir": "src",
"declaration": true,
"sourceMap": true,
"esModuleInterop": true,
"skipLibCheck": true,
"baseUrl": ".",
"paths": { "@/*": ["src/*"] }
},
"include": ["src"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
关键点
- **
files/include/exclude** 决定参与编译的文件;exclude只对include生效,files显式列出的不受影响。 - **
extends** 继承公共配置("extends": "./tsconfig.base.json"),多包仓库常用。 - **
references** 项目引用做增量构建(monorepo)。 - 编辑器(VS Code)读取最近的
tsconfig.json,路径别名不生效往往是这里没配或baseUrl不对。 tsc --showConfig可打印最终合并后的配置,排查继承问题很好用。- 只做类型检查、产物交给 Vite/esbuild 时用
noEmit: true。
没有它会怎样
tsc 会用默认配置(ES3/ES5 目标、非严格模式、编译当前目录所有 .ts),几乎不符合现代项目需求;编辑器也失去路径别名与严格检查,退化成"只高亮语法"。