Skip to content

附录B TypeScript配置文件详解

本附录详细说明tsconfig.json的各个配置选项,帮助你理解和配置TypeScript项目。


{
"compilerOptions": { /* 编译选项 */ },
"include": [ /* 要编译的文件 */ ],
"exclude": [ /* 排除的文件 */ ],
"extends": "base.json", // 继承其他配置
"files": [ /* 显式指定要编译的文件 */ ],
"references": [ /* 项目引用 */ ]
}
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}

指定编译出的JavaScript版本:

{
"target": "ES2020" // 可选:ES3, ES5, ES6/ES2015, ES2016, ES2017, ES2018, ES2019, ES2020, ES2021, ESNext
}

推荐:ES2020或更高版本,除非需要兼容旧浏览器。

{
"module": "commonjs" // 可选:none, commonjs, amd, umd, system, es6/es2015, es2020, esnext, node16, nodenext
}
值用途
commonjsNode.js(向后兼容)
es2015/es2020ES Module(现代浏览器)
node16Node.js 16+原生支持
nodenext最新Node.js
{
"lib": ["ES2020", "DOM", "DOM.Iterable"]
}

常用值:

  • ES2020、ES2021、ES2022、ESNext
  • DOM、DOM.Iterable
  • WebWorker
  • ScriptHost
  • DOM.Iterable
{
"outDir": "./dist", // 输出目录
"rootDir": "./src" // 源码目录
}
{
"outFile": "./bundle.js", // 合并为单个文件(仅amd/system)
"removeComments": true, // 移除注释
"noEmit": false, // 不生成输出文件
"declaration": true, // 生成.d.ts声明文件
"declarationDir": "./types", // 声明文件输出目录
"sourceMap": true, // 生成source map
"inlineSourceMap": false, // 内联source map
"emitBOM": false, // 添加UTF-8 BOM
"newLine": "lf" // 行尾符:lf, crlf, native
}

{
"strict": true
}

启用所有严格类型检查选项,等价于以下所有:

  • strictNullChecks
  • strictPropertyInitialization
  • noImplicitAny
  • noImplicitThis
  • alwaysStrict
  • strictBindCallApply
  • strictFunctionTypes

不允许隐式any类型:

{
"noImplicitAny": true
}
// 错误:参数隐式any
function process(x) { // Error: Parameter 'x' implicitly has an 'any' type
return x;
}
// 正确:显式标注或推断
function process(x: string) {
return x;
}

严格null/undefined检查:

{
"strictNullChecks": true
}
// 错误:可能为null
function getLength(str: string | null) {
return str.length; // Error: 'str' is possibly 'null'
}
// 正确:先检查
function getLength(str: string | null) {
if (str === null) return 0;
return str.length;
}

确保类的属性被初始化:

{
"strictPropertyInitialization": true
}
// 错误
class User {
name: string; // Error: Property 'name' has no initializer
}
// 正确
class User {
name: string = "";
}
{
"noUnusedLocals": true, // 未使用的局部变量报错
"noUnusedParameters": true, // 未使用的参数报错
"noImplicitReturns": true, // 函数有分支未返回值
"noFallthroughCasesInSwitch": true, // switch case必须有break
"noUncheckedIndexedAccess": true, // 数组元素可能undefined
"allowUnreachableCode": false, // 不可达代码报错
"allowUnusedLabels": false // 未使用标签报错
}

模块解析策略:

{
"moduleResolution": "node" // 可选:classic, node, node16, nodenext
}

推荐:node或node16/nodenext(Node.js 16+)

路径别名配置:

{
"baseUrl": "./src",
"paths": {
"@utils/*": ["utils/*"],
"@components/*": ["components/*"],
"@/*": ["./*"]
}
}

使用:

import { format } from "@utils/format";

多个源目录映射到同一个输出目录:

{
"rootDirs": ["src", "generated"]
}

指定类型声明目录:

{
"typeRoots": ["./node_modules/@types", "./types"],
"types": ["node", "jest"]
}

允许和检查JavaScript文件:

{
"allowJs": true, // 允许编译JS文件
"checkJs": true, // 检查JS类型错误
"maxNodeModuleJsDepth": 2 // 检查node_modules中JS的深度
}

JSX处理模式(用于React):

{
"jsx": "react-jsx" // 可选:preserve, react, react-native, react-jsx, react-jsxdev
}
值说明
preserve保留JSX,输出.jsx文件
react编译为React.createElement
react-jsx使用新的JSX转换(React 17+)
react-jsxdev开发模式

{
"experimentalDecorators": true, // 启用装饰器
"emitDecoratorMetadata": true, // 装饰器元数据
"emitDeclarationOnly": false, // 只输出声明文件
"incremental": true, // 增量编译
"tsBuildInfoFile": "./.tsbuildinfo", // 增量编译信息文件
"useDefineForClassFields": false // 使用define代替constructor
}
{
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
@sealed
class Greeter {
@format("Hello, %s")
greeting: string;
}

跳过库类型检查(加速编译):

{
"skipLibCheck": true
}

推荐:生产项目中设为true,避免第三方库类型冲突。

文件名大小写一致性检查:

{
"forceConsistentCasingInFileNames": true
}

单文件隔离检查:

{
"isolatedModules": true
}

确保每个文件可以单独编译,用于webpack等打包工具。

允许导入JSON文件:

{
"resolveJsonModule": true
}
import config from "./config.json";

允许默认导入风格互操作:

{
"esModuleInterop": true
}
import fs from "fs"; // 正确工作

允许合成默认导入:

{
"allowSyntheticDefaultImports": true
}

通常与esModuleInterop一起使用。


{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"jsx": "react-jsx",
"strict": true,
"moduleResolution": "node",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"skipLibCheck": true
}
}
{
"compilerOptions": {
"target": "ES2020",
"module": "Node16",
"moduleResolution": "node16",
"lib": ["ES2020"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"outDir": "./dist",
"rootDir": "./src",
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
{
"compilerOptions": {
"target": "ES2020",
"module": "ES2020",
"lib": ["ES2020"],
"declaration": true,
"declarationMap": true,
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"outDir": "./dist",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
{
"compilerOptions": {
"target": "ES5",
"module": "commonjs",
"lib": ["ES5", "DOM"],
"jsx": "react",
"strict": false,
"noImplicitAny": false,
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "./dist"
}
}

继承其他配置:

{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"outDir": "./custom-out"
}
}

项目引用:

{
"references": [
{ "path": "../shared" }
]
}

被引用项目的tsconfig.json需要:

{
"compilerOptions": {
"composite": true,
"declarationMap": true
}
}

Terminal window
# 检查tsconfig.json语法
npx tsc --showConfig
# 编译并检查
npx tsc --noEmit
# 详细输出
npx tsc --listEmittedFiles
  1. 找不到模块:检查moduleResolution和baseUrl
  2. 类型冲突:检查skipLibCheck
  3. 装饰器报错:启用experimentalDecorators

下一节将介绍进阶学习资源与社区。