附录B TypeScript配置文件详解
本附录详细说明tsconfig.json的各个配置选项,帮助你理解和配置TypeScript项目。
B.1 tsconfig.json基础
Section titled “B.1 tsconfig.json基础”{ "compilerOptions": { /* 编译选项 */ }, "include": [ /* 要编译的文件 */ ], "exclude": [ /* 排除的文件 */ ], "extends": "base.json", // 继承其他配置 "files": [ /* 显式指定要编译的文件 */ ], "references": [ /* 项目引用 */ ]}常见配置示例
Section titled “常见配置示例”{ "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"]}B.2 compilerOptions详解
Section titled “B.2 compilerOptions详解”target - 编译目标
Section titled “target - 编译目标”指定编译出的JavaScript版本:
{ "target": "ES2020" // 可选:ES3, ES5, ES6/ES2015, ES2016, ES2017, ES2018, ES2019, ES2020, ES2021, ESNext}推荐:ES2020或更高版本,除非需要兼容旧浏览器。
module - 模块系统
Section titled “module - 模块系统”{ "module": "commonjs" // 可选:none, commonjs, amd, umd, system, es6/es2015, es2020, esnext, node16, nodenext}| 值 | 用途 |
|---|---|
commonjs | Node.js(向后兼容) |
es2015/es2020 | ES Module(现代浏览器) |
node16 | Node.js 16+原生支持 |
nodenext | 最新Node.js |
lib - 内置库
Section titled “lib - 内置库”{ "lib": ["ES2020", "DOM", "DOM.Iterable"]}常用值:
ES2020、ES2021、ES2022、ESNextDOM、DOM.IterableWebWorkerScriptHostDOM.Iterable
outDir 与 rootDir
Section titled “outDir 与 rootDir”{ "outDir": "./dist", // 输出目录 "rootDir": "./src" // 源码目录}其他输出选项
Section titled “其他输出选项”{ "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}B.3 类型检查选项
Section titled “B.3 类型检查选项”strict - 严格模式
Section titled “strict - 严格模式”{ "strict": true}启用所有严格类型检查选项,等价于以下所有:
strictNullChecksstrictPropertyInitializationnoImplicitAnynoImplicitThisalwaysStrictstrictBindCallApplystrictFunctionTypes
noImplicitAny
Section titled “noImplicitAny”不允许隐式any类型:
{ "noImplicitAny": true}// 错误:参数隐式anyfunction process(x) { // Error: Parameter 'x' implicitly has an 'any' type return x;}
// 正确:显式标注或推断function process(x: string) { return x;}strictNullChecks
Section titled “strictNullChecks”严格null/undefined检查:
{ "strictNullChecks": true}// 错误:可能为nullfunction 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
Section titled “strictPropertyInitialization”确保类的属性被初始化:
{ "strictPropertyInitialization": true}// 错误class User { name: string; // Error: Property 'name' has no initializer}
// 正确class User { name: string = "";}其他检查选项
Section titled “其他检查选项”{ "noUnusedLocals": true, // 未使用的局部变量报错 "noUnusedParameters": true, // 未使用的参数报错 "noImplicitReturns": true, // 函数有分支未返回值 "noFallthroughCasesInSwitch": true, // switch case必须有break "noUncheckedIndexedAccess": true, // 数组元素可能undefined "allowUnreachableCode": false, // 不可达代码报错 "allowUnusedLabels": false // 未使用标签报错}B.4 模块解析选项
Section titled “B.4 模块解析选项”moduleResolution
Section titled “moduleResolution”模块解析策略:
{ "moduleResolution": "node" // 可选:classic, node, node16, nodenext}推荐:node或node16/nodenext(Node.js 16+)
baseUrl 与 paths
Section titled “baseUrl 与 paths”路径别名配置:
{ "baseUrl": "./src", "paths": { "@utils/*": ["utils/*"], "@components/*": ["components/*"], "@/*": ["./*"] }}使用:
import { format } from "@utils/format";rootDirs
Section titled “rootDirs”多个源目录映射到同一个输出目录:
{ "rootDirs": ["src", "generated"]}typeRoots 与 types
Section titled “typeRoots 与 types”指定类型声明目录:
{ "typeRoots": ["./node_modules/@types", "./types"], "types": ["node", "jest"]}B.5 JavaScript支持
Section titled “B.5 JavaScript支持”allowJs 与 checkJs
Section titled “allowJs 与 checkJs”允许和检查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 | 开发模式 |
B.6 实验性选项
Section titled “B.6 实验性选项”{ "experimentalDecorators": true, // 启用装饰器 "emitDecoratorMetadata": true, // 装饰器元数据 "emitDeclarationOnly": false, // 只输出声明文件 "incremental": true, // 增量编译 "tsBuildInfoFile": "./.tsbuildinfo", // 增量编译信息文件 "useDefineForClassFields": false // 使用define代替constructor}{ "experimentalDecorators": true, "emitDecoratorMetadata": true}@sealedclass Greeter { @format("Hello, %s") greeting: string;}B.7 高级选项
Section titled “B.7 高级选项”skipLibCheck
Section titled “skipLibCheck”跳过库类型检查(加速编译):
{ "skipLibCheck": true}推荐:生产项目中设为true,避免第三方库类型冲突。
forceConsistentCasingInFileNames
Section titled “forceConsistentCasingInFileNames”文件名大小写一致性检查:
{ "forceConsistentCasingInFileNames": true}isolatedModules
Section titled “isolatedModules”单文件隔离检查:
{ "isolatedModules": true}确保每个文件可以单独编译,用于webpack等打包工具。
resolveJsonModule
Section titled “resolveJsonModule”允许导入JSON文件:
{ "resolveJsonModule": true}import config from "./config.json";esModuleInterop
Section titled “esModuleInterop”允许默认导入风格互操作:
{ "esModuleInterop": true}import fs from "fs"; // 正确工作allowSyntheticDefaultImports
Section titled “allowSyntheticDefaultImports”允许合成默认导入:
{ "allowSyntheticDefaultImports": true}通常与esModuleInterop一起使用。
B.8 推荐配置方案
Section titled “B.8 推荐配置方案”现代浏览器项目
Section titled “现代浏览器项目”{ "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 }}Node.js项目
Section titled “Node.js项目”{ "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"]}旧浏览器兼容
Section titled “旧浏览器兼容”{ "compilerOptions": { "target": "ES5", "module": "commonjs", "lib": ["ES5", "DOM"], "jsx": "react", "strict": false, "noImplicitAny": false, "moduleResolution": "node", "esModuleInterop": true, "skipLibCheck": true, "outDir": "./dist" }}B.9 配置继承与引用
Section titled “B.9 配置继承与引用”extends
Section titled “extends”继承其他配置:
{ "extends": "./tsconfig.base.json", "compilerOptions": { "outDir": "./custom-out" }}references
Section titled “references”项目引用:
{ "references": [ { "path": "../shared" } ]}被引用项目的tsconfig.json需要:
{ "compilerOptions": { "composite": true, "declarationMap": true }}B.10 配置验证
Section titled “B.10 配置验证”# 检查tsconfig.json语法npx tsc --showConfig
# 编译并检查npx tsc --noEmit
# 详细输出npx tsc --listEmittedFiles- 找不到模块:检查
moduleResolution和baseUrl - 类型冲突:检查
skipLibCheck - 装饰器报错:启用
experimentalDecorators
下一节将介绍进阶学习资源与社区。