5 天以前 687fdb6d320da85a4702fbd1af95ff4a131c7612
refactor(multiple-build): 重构构建脚本以支持多公司配置

- 替换单引号为双引号以统一代码风格
- 优化公司参数解析逻辑,支持命令行参数、npm配置和环境变量
- 添加公司配置验证,提供可用选项提示
- 改进参数解析函数,支持更多参数格式
- 重构配置映射循环逻辑,提高代码可读性
- 添加默认公司回退机制,增强脚本健壮性
已修改1个文件
177 ■■■■■ 文件已修改
multiple/multiple-build.js 177 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
multiple/multiple-build.js
@@ -1,98 +1,137 @@
import fs from 'fs/promises';
import fsSync from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from "fs/promises";
import fsSync from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { execSync } from "child_process";
// 获取 __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// 读取 JSON 配置
const data = await fs.readFile(path.join(__dirname, 'config.json'), 'utf-8');
const data = await fs.readFile(path.join(__dirname, "config.json"), "utf-8");
const config = JSON.parse(data);
// 项目路径
const rootPath = path.resolve(__dirname, '..');
const resourcePath = path.join(rootPath, 'multiple', 'assets');
const replacePath = path.join(rootPath, 'replace');
const rootPath = path.resolve(__dirname, "..");
const resourcePath = path.join(rootPath, "multiple", "assets");
const replacePath = path.join(rootPath, "replace");
const envFilePath = path.join(rootPath, ".env.production.local");
// 获取命令行参数
const params = parseArgs(process.argv);
const company = params["company"] ?? "default";
const company = resolveCompany(params);
const companyMap = config[company];
const envFilePath = path.join(process.cwd(), '.env.production.local');
if (!companyMap) {
  const availableCompanies = Object.entries(config)
    .filter(([, value]) => value && typeof value === "object" && value.env)
    .map(([key]) => key)
    .sort();
  throw new Error(
    `未知 company: "${company}"。可选值: ${availableCompanies.join(", ")}`
  );
}
console.log(`当前 company: ${company}`);
async function copyFileWithOverwrite(src, dest) {
    await fs.mkdir(path.dirname(dest), { recursive: true });
    if (fsSync.existsSync(dest)) {
        try {
            await fs.chmod(dest, 0o666);
        } catch {
            // Ignore chmod failure and try delete directly.
        }
        await fs.rm(dest, { force: true });
  await fs.mkdir(path.dirname(dest), { recursive: true });
  if (fsSync.existsSync(dest)) {
    try {
      await fs.chmod(dest, 0o666);
    } catch {
      // Ignore chmod failure and continue.
    }
    await fs.copyFile(src, dest);
    await fs.rm(dest, { force: true });
  }
  await fs.copyFile(src, dest);
}
try {
    // 1️⃣ 生成 .env
    console.log("=======生成.env=======");
    const envContent = Object.entries(companyMap.env)
        .map(([key, value]) => `${key}='${value}'`)
        .join('\n') + '\n';
    await fs.writeFile(envFilePath, envContent, 'utf-8');
  console.log("=======生成.env=======");
  const envContent =
    Object.entries(companyMap.env)
      .map(([key, value]) => `${key}='${value}'`)
      .join("\n") + "\n";
  await fs.writeFile(envFilePath, envContent, "utf-8");
    // 2️⃣ 备份原始资源并替换
    console.log("=======修改资源=======");
    for (const [key, value] of Object.entries(companyMap)) {
        if (key === 'env') continue;
  console.log("=======修改资源=======");
  for (const [key] of Object.entries(companyMap)) {
    if (key === "env") continue;
        const originFile = path.join(rootPath, config[key]);
        const backupFile = path.join(replacePath, config[key]);
        const replaceFile = path.join(resourcePath, companyMap[key]);
    const originFile = path.join(rootPath, config[key]);
    const backupFile = path.join(replacePath, config[key]);
    const replaceFile = path.join(resourcePath, companyMap[key]);
        await copyFileWithOverwrite(originFile, backupFile);
        await copyFileWithOverwrite(replaceFile, originFile);
    }
    await copyFileWithOverwrite(originFile, backupFile);
    await copyFileWithOverwrite(replaceFile, originFile);
  }
    console.log("=====开始打包======");
    execSync("vite build", { stdio: "inherit" });
    console.log("=====打包完成======");
  console.log("=====开始打包=====");
  execSync("vite build", { stdio: "inherit" });
  console.log("=====打包完成======");
} finally {
    console.log("=====恢复资源======");
  console.log("=====恢复资源======");
    // 删除临时 .env 文件
    if (fsSync.existsSync(envFilePath)) {
        await fs.unlink(envFilePath);
        console.log(`🗑️ 已删除 ${envFilePath}`);
  if (fsSync.existsSync(envFilePath)) {
    await fs.unlink(envFilePath);
    console.log(`🗑️ 已删除 ${envFilePath}`);
  }
  if (fsSync.existsSync(replacePath)) {
    for (const [key] of Object.entries(companyMap)) {
      if (key === "env") continue;
      const originFile = path.join(rootPath, config[key]);
      const backupFile = path.join(replacePath, config[key]);
      await copyFileWithOverwrite(backupFile, originFile);
    }
    // 恢复资源文件
    if (fsSync.existsSync(replacePath)) {
        for (const [key, value] of Object.entries(companyMap)) {
            if (key === 'env') continue;
            const originFile = path.join(rootPath, config[key]);
            const backupFile = path.join(replacePath, config[key]);
            await copyFileWithOverwrite(backupFile, originFile);
        }
        await fs.rm(replacePath, { recursive: true, force: true });
        console.log(`🗑️ 已删除 ${replacePath}`);
    }
    await fs.rm(replacePath, { recursive: true, force: true });
    console.log(`🗑️ 已删除 ${replacePath}`);
  }
}
// 简单命令行参数解析
function parseArgs(argv) {
    const params = {};
    for (const arg of argv.slice(2)) {
        if (arg.startsWith('--')) {
            const [key, value] = arg.slice(2).split('=');
            params[key] = value ?? true;
        }
  const params = {};
  for (let index = 2; index < argv.length; index++) {
    const arg = argv[index];
    if (!arg.startsWith("--")) continue;
    const normalized = arg.slice(2);
    const equalIndex = normalized.indexOf("=");
    if (equalIndex >= 0) {
      const key = normalized.slice(0, equalIndex);
      const value = normalized.slice(equalIndex + 1);
      params[key] = value || true;
      continue;
    }
    return params;
    const nextArg = argv[index + 1];
    if (nextArg && !nextArg.startsWith("--")) {
      params[normalized] = nextArg;
      index += 1;
      continue;
    }
    params[normalized] = true;
  }
  return params;
}
function resolveCompany(parsedParams) {
  const fromArg = parseValue(parsedParams.company);
  if (fromArg) return fromArg;
  const fromNpmConfig = parseValue(process.env.npm_config_company);
  if (fromNpmConfig) return fromNpmConfig;
  const fromEnv = parseValue(process.env.COMPANY ?? process.env.company);
  if (fromEnv) return fromEnv;
  return "default";
}
function parseValue(value) {
  if (value == null || value === true) return undefined;
  if (typeof value !== "string") return undefined;
  const trimmed = value.trim();
  if (!trimmed) return undefined;
  return trimmed.replace(/^["']|["']$/g, "");
}