cleanApp.js 1.78 KB
import fs from 'node:fs';
import path from 'node:path';

// Usage:
//   node scripts/cleanApp.js vue <name> [--dir=apps/frontend/vue] [--subdir=playground]
//   node scripts/cleanApp.js react <name> [--dir=apps/frontend/react] [--subdir=playground]
//   node scripts/cleanApp.js path --path=apps/frontend/vue/my-app-vue
//   node scripts/cleanApp.js <template> <name> [--dir=<relative base>] [--subdir=<sub path>]

const args = process.argv.slice(2);
const template = (args[0] || 'vue').toLowerCase();
const flags = args.filter((a) => typeof a === 'string' && a.startsWith('--'));
const positionals = args
  .filter((a) => typeof a === 'string' && !a.startsWith('--'))
  .slice(1); // drop template

const dirArg = flags.find((a) => a.startsWith('--dir='));
const subdirArg = flags.find((a) => a.startsWith('--subdir='));
const pathArg = flags.find((a) => a.startsWith('--path='));

const defaultBase =
  template === 'react' ? 'apps/frontend/react' : 'apps/frontend/vue';

let target;

if (pathArg) {
  const rel = pathArg.slice('--path='.length);
  target = path.resolve(process.cwd(), rel);
} else {
  const name = positionals[0];
  if (!name) {
    console.error('请提供要清理的项目名。例如: pnpm run clean:vue my-app-vue');
    process.exit(1);
  }

  let base = dirArg ? dirArg.slice('--dir='.length) : defaultBase;
  if (subdirArg) {
    base = path.join(base, subdirArg.slice('--subdir='.length));
  }

  target = path.resolve(process.cwd(), base, name);
}

try {
  if (!fs.existsSync(target)) {
    console.log(`目标目录不存在,已跳过: ${target}`);
    process.exit(0);
  }

  fs.rmSync(target, { recursive: true, force: true });
  console.log(`已清理: ${target}`);
  process.exit(0);
} catch (error) {
  console.error(`清理失败: ${error?.message || error}`);
  process.exit(1);
}