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 config = JSON.parse(data); // 项目路径 const rootPath = path.resolve(__dirname, '..'); const resourcePath = path.join(rootPath, 'multiple', 'assets'); const replacePath = path.join(rootPath, 'replace'); // 获取命令行参数 const params = parseArgs(process.argv); const company = params["company"] ?? "default"; const companyMap = config[company]; const envFilePath = path.join(process.cwd(), '.env.production.local'); 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'); // 2️⃣ 备份原始资源并替换 console.log("=======修改资源======="); 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]); const replaceFile = path.join(resourcePath, companyMap[key]); await fs.mkdir(path.dirname(backupFile), { recursive: true }); await fs.copyFile(originFile, backupFile); await fs.copyFile(replaceFile, originFile); } console.log("=====开始打包======"); execSync("vite build", { stdio: "inherit" }); console.log("=====打包完成======"); } finally { console.log("=====恢复资源======"); // 删除临时 .env 文件 if (fsSync.existsSync(envFilePath)) { await fs.unlink(envFilePath); console.log(`🗑️ 已删除 ${envFilePath}`); } // 恢复资源文件 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 fs.copyFile(backupFile, originFile); } 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; } } return params; }