← 返回完整题库
Typescript困难

如何管理和优化 tsconfig?

参考答案

tsconfig 是什么

tsconfig.json 是 TS 项目的编译配置,tsc 靠它确定编译范围、目标产物、类型检查强度、路径映射。可用 tsc --init 生成,支持 extends 继承。

常用字段

{
  "compilerOptions": {
    "target": "ES2020",          // 输出语法目标
    "module": "ESNext",          // 模块规范
    "moduleResolution": "Bundler",
    "lib": ["ES2020", "DOM"],
    "strict": true,              // 打开全部严格检查(推荐)
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUnusedLocals": true,
    "esModuleInterop": true,
    "skipLibCheck": true,        // 跳过 .d.ts 检查,提速
    "isolatedModules": true,
    "forceConsistentCasingInFileNames": true,
    "baseUrl": ".",
    "paths": { "@/*": ["src/*"] },
    "declaration": true,
    "sourceMap": true,
    "outDir": "dist",
    "incremental": true,         // 增量编译缓存
    "noEmit": true               // 只做类型检查(交给 Vite/ESBuild 产出)
  },
  "include": ["src/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

管理与优化

  1. 分层继承:tsconfig.base.json 放公共配置,项目/包用 extends 覆盖,多包仓库统一基线。
  2. 按环境分文件:tsconfig.json(开发/编辑器)、tsconfig.build.json(发布,排除测试)、tsconfig.test.json。
  3. 拆项目引用:大仓库用 references + composite 做增量构建,只重编改动包。
  4. 提速:skipLibCheck、incremental、assumeChangesOnlyAffectDirectDependencies、控制 include 范围(别把整个仓库纳入)。
  5. 一致性:开启 strict、noUncheckedIndexedAccess、exactOptionalPropertyTypes 逐步收紧;forceConsistentCasingInFileNames 避免大小写坑。
  6. 避免重复:paths 与打包器 alias 保持一致,防止编辑器能跳转、运行时却找不到。

易错点

target 影响 lib 的默认值;noEmit 与 outDir 不要同时期待产物;skipLibCheck 会漏掉第三方类型冲突,排查时可临时关闭。

本题来自 计算机知识面试题库,共 921 道题。