dev.mjs 3.01 KB
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

/**
 * 一条命令起全站,开发者只访问 http://localhost:5173。
 *
 * wujie 的子应用必须有自己的 dev server 才有 HMR,进程数确实变多;
 * 但入口仍是一个命令、一个浏览器地址 —— 符合「一个前端」的既有要求。
 * 服务启停由人控制:本脚本不常驻、不自动拉起,Ctrl+C 会把所有子进程一起收掉。
 *
 * 用法:
 *   pnpm dev                        # shell + system + store
 *   pnpm dev --scope=shell          # 只起主壳
 *   pnpm dev --scope=store          # 只起门店域
 */
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const argv = process.argv.slice(2);
const scopeArg = argv.find((a) => a.startsWith('--scope='));
const scope = scopeArg ? scopeArg.slice('--scope='.length).split(',') : null;

function collectApps(dir) {
  const out = [];
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    if (!entry.isDirectory() || entry.name === 'node_modules' || entry.name === 'dist') continue;
    const pkgPath = path.join(dir, entry.name, 'package.json');
    if (fs.existsSync(pkgPath)) {
      const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
      if (pkg.scripts?.dev)
        out.push({
          name: pkg.name,
          short: pkg.name.replace('@uj/web-', ''),
          dir: path.relative(ROOT, path.dirname(pkgPath)),
        });
    } else {
      out.push(...collectApps(path.join(dir, entry.name)));
    }
  }
  return out;
}

const apps = collectApps(path.join(ROOT, 'apps', 'web')).filter(
  (a) => !scope || scope.includes(a.short),
);

if (apps.length === 0) {
  console.error('[dev] 没有找到可启动的应用,检查 apps/web 下的 package.json。');
  process.exit(1);
}

console.log('[dev] 启动应用:');
for (const a of apps) console.log(`  - ${a.name.padEnd(20)} ${a.dir}`);
console.log('[dev] 浏览器入口:http://localhost:5173  (Ctrl+C 停止全部)');
console.log('');

const children = [];
for (const a of apps) {
  const child = spawn('pnpm', ['--filter', a.name, 'dev'], {
    cwd: ROOT,
    shell: true,
    stdio: ['ignore', 'pipe', 'pipe'],
    env: { ...process.env, FORCE_COLOR: '1' },
  });
  const prefix = `[${a.short}] `;
  child.stdout.on('data', (buf) => {
    for (const line of String(buf).split(/\r?\n/)) if (line) console.log(prefix + line);
  });
  child.stderr.on('data', (buf) => {
    for (const line of String(buf).split(/\r?\n/)) if (line) console.error(prefix + line);
  });
  child.on('exit', (code) => {
    if (code && code !== 0) console.error(`[dev] ${a.name} 退出,code=${code}`);
  });
  children.push(child);
}

function shutdown() {
  console.log('\n[dev] 正在停止全部子进程…');
  for (const child of children) {
    try {
      child.kill('SIGTERM');
    } catch {
      /* 已退出 */
    }
  }
  process.exit(0);
}

process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);