gen-tsconfig.mjs 1.93 KB
import fs from 'node:fs';
import path from 'node:path';
import { ROOT, createTsconfigPaths } from '../packages/vite-config/src/aliases.mjs';

/**
 * 从 alias 单一真源生成各 app 的 tsconfig.json。
 *
 * 为什么要生成而不是手写:Vite 的 resolve.alias 与 TS 的 paths 必须看到同一张表。
 * 手抄两份的结果一定是「dev 能跑、tsc 报找不到模块」,而且错法很隐蔽。
 * 新增子应用时在 APPS 里加一行重跑即可。
 */
const APPS = [
  { dir: 'apps/web/shell', kind: 'shell' },
  { dir: 'apps/web/micro-apps/system', kind: 'subapp' },
  { dir: 'apps/web/micro-apps/store', kind: 'subapp' },
];

for (const { dir, kind } of APPS) {
  const appDir = path.join(ROOT, dir);
  const extendsPath = path
    .relative(appDir, path.join(ROOT, 'packages/typescript-config/react-app.json'))
    .split(path.sep)
    .join('/');

  const include = ['src/**/*.ts', 'src/**/*.tsx', 'src/**/*.d.ts', 'vite.config.ts'];
  // shell 会把 platform-core 的源码纳入自己的编译程序(paths 直指源码),
  // 因此也必须纳入它的 ambient 声明:PEM 虚拟模块只在那里声明一次,
  // 否则 config.ts 的 `import ... from 'virtual:...'` 报 TS2307。
  // 不在 shell 里复制声明,是为了避免同名 ambient module 重复声明冲突。
  if (kind === 'shell') {
    include.push(
      path
        .relative(appDir, path.join(ROOT, 'packages/platform-core/src/vite-env.d.ts'))
        .split(path.sep)
        .join('/'),
    );
  }

  const config = {
    extends: extendsPath.startsWith('.') ? extendsPath : `./${extendsPath}`,
    compilerOptions: {
      baseUrl: '.',
      paths: createTsconfigPaths({ appDir, kind }),
    },
    include,
  };

  const dest = path.join(appDir, 'tsconfig.json');
  fs.mkdirSync(appDir, { recursive: true });
  fs.writeFileSync(dest, `${JSON.stringify(config, null, 2)}\n`, 'utf8');
  console.log(`[gen:tsconfig] ${dir}/tsconfig.json (${kind})`);
}