如何合并多个项目的 tsconfig 引用?

解读

在国内中大型前端团队里,“一个仓库多个子包”(monorepo)已成标配:PC 管理后台、H5 商城、小程序 SDK、组件库各自是独立项目,却共用工具函数、枚举、接口定义。每个子包都有自己的 tsconfig.json,如果让 Gulp 统一走一次 TypeScript 编译,必须先把散落在各包的配置合并成一份“虚拟配置”,否则 tsc 会反复跳盘、路径解析失败,甚至把 node_modules 类型重复引入,导致 CI 超时。
面试官问“合并 tsconfig”,表面看是 TypeScript 话题,实则考察候选人是否理解 Gulp 的 Vinyl 流式思想:用代码把“多份物理配置”转成“一份内存配置”,再喂给 gulp-typescript、gulp-bro 或 tsc 插件,实现一次管道、全仓库类型检查与输出。

知识点

  1. Project References 机制:tsconfig.json 里的 references 数组允许把子包当成独立子工程,tsc -b 会按依赖图并行编译;但 Gulp 默认是单进程流,需要把 references 展开成真实文件列表。
  2. Vinyl 虚拟文件系统:Gulp 管道里流转的是 Vinyl 对象,不是磁盘文件;合并配置时要把各子包 tsconfig.json 读成 JSON → 深度合并 → 生成新的 Vinyl 对象,路径全部改成绝对路径,否则 gulp.dest 阶段会写错位置。
  3. extends 链式继承:国内很多团队把 @company/tsconfig-base 发布到私有 npm,子包 extends 它;合并时必须递归拉取 extends 内容,并把 baseUrl、paths 按包名+子路径重新映射,否则 import '@utils/http' 会解析不到。
  4. gulp-typescript 插件限制:它只认一份 tsconfig.json 路径,不支持数组;因此合并后需要临时写到内存文件系统(memfs) 或 /tmp/tsconfig.merged.json,再传给插件,避免污染源码。
  5. 增量编译与缓存:国内 CI 按“合并 → 编译 → 上传产物”三步跑,合并阶段必须做内容哈希缓存(把合并后的 JSON 字符串 md5),哈希不变就跳过,节省 30%~50% 流水线时间。

答案

下面给出一段可直接落地的 Gulp 任务,兼顾私有 npm 场景与monorepo 场景,全部用 Node 原生 API 与 through2,不依赖第三方合并库,方便在面试时手写。

// gulpfile.ts
import { src, dest, series } from 'gulp';
import * as through2 from 'through2';
import * as path from 'path';
import * as fs from 'fs';
import * as crypto from 'crypto';
import * as ts from 'gulp-typescript';

const root = process.cwd();
const mergeCache = new Map<string, string>();

/**
 * 递归读取 extends 并把 paths、baseUrl 按包名重新映射
 */
function loadTsConfig(file: string, visited = new Set<string>()): any {
  if (visited.has(file)) return {};
  visited.add(file);
  const raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
  if (raw.extends) {
    const extendPath = require.resolve(raw.extends, { paths: [path.dirname(file)] });
    const parent = loadTsConfig(extendPath, visited);
    raw.compilerOptions = Object.assign({}, parent.compilerOptions, raw.compilerOptions);
    // 国内习惯:私有包以 @company 开头,需要把 paths 拼成绝对路径
    if (raw.compilerOptions.paths) {
      Object.keys(raw.compilerOptions.paths).forEach(k => {
        raw.compilerOptions.paths[k] = raw.compilerOptions.paths[k].map((v: string) =>
          path.resolve(path.dirname(file), v)
        );
      });
    }
  }
  return raw;
}

/**
 * 把多个子包 tsconfig 合并成一份虚拟配置
 */
function mergeTsConfig() {
  return src(['packages/*/tsconfig.json', 'apps/*/tsconfig.json'], { cwd: root })
    .pipe(through2.obj(function (file, _, cb) {
      const cfg = loadTsConfig(file.path);
      // 生成唯一 key:文件列表 + 内容哈希
      const key = crypto.createHash('md5')
        .update(JSON.stringify(cfg))
        .digest('hex');
      if (mergeCache.has(key)) return cb(); // 命中缓存
      mergeCache.set(key, JSON.stringify(cfg));
      // 写到内存路径,供下一步 gulp-typescript 使用
      const mergedPath = path.join(root, 'node_modules/.cache/tsconfig', `${key}.json`);
      fs.mkdirSync(path.dirname(mergedPath), { recursive: true });
      fs.writeFileSync(mergedPath, JSON.stringify(cfg, null, 2));
      file.path = mergedPath; // 把 vinyl 路径指向合并后的文件
      cb(null, file);
    }));
}

/**
 * 使用合并后的配置执行一次全仓库类型检查 + 输出
 */
function compileWithMerged() {
  // 从缓存目录读取最新一份合并配置
  const [cached] = fs.readdirSync(path.join(root, 'node_modules/.cache/tsconfig'));
  const tsProject = ts.createProject(path.join(root, 'node_modules/.cache/tsconfig', cached), {
    typescript: require('typescript') // 锁定团队统一版本
  });
  return src(['packages/*/src/**/*.{ts,tsx}', 'apps/*/src/**/*.{ts,tsx}'], { cwd: root })
    .pipe(tsProject())
    .pipe(dest('dist')); // 统一输出到 dist,按子包名分文件夹
}

export const build = series(mergeTsConfig, compileWithMerged);

关键点说明

  1. 缓存目录放在 node_modules/.cache,CI 默认会清理,符合国内 Jenkins/GitLab Runner 规范。
  2. 路径重写阶段把 paths 全部转绝对路径,避免 Windows 与 macOS 大小写问题。
  3. 如果子包用了 references,可在 loadTsConfig 里把 references 数组展平成 include,再合并,确保 gulp-typescript 一次跑通。
  4. 面试时手写至此,可再补一句:“后续会把这段逻辑封装成公司私有 gulp 插件,发布到内部 npm,供所有业务线复用。” 体现工程化思维。

拓展思考

  1. 与 Vite/Webpack 的“库模式”如何协同?
    国内很多团队用 Vite 做 H5,用 Gulp 做组件库打包。可以在 Gulp 里把合并后的 tsconfig 直接写到 vite.config.ts 的 resolve.alias 字段,实现类型与运行时路径统一,避免 tsc 过了但 Vite 报找不到模块。

  2. 如何支持“子包独立版本”场景?
    如果子包要走独立发包(changesets),合并配置时需把 compilerOptions.declarationDir 指向 packages/xxx/dist/types,并在 Gulp 里追加 gulp-dts 任务,把每个子包的 .d.ts 抽离到各自目录,否则发布到私有 npm 后类型路径会失效。

  3. 增量编译再提速:
    在合并阶段把每个子包最后一次 git commit 哈希也写进缓存 key,只有代码变更的子包才触发合并,CI 平均可再省 40 秒;再配合 nx affected:libs 做精准测试,国内头部厂已把 10 分钟流水线压到 3 分钟以内。