const { execSync } = require("child_process") const path = require("path") const fs = require("fs") /** * 压缩前端打包文件 * 压缩包放在根目录下,文件名格式: competition-web-{env}-v{version}.tgz * * 用法: * node scripts/compress.cjs test - 测试环境 * node scripts/compress.cjs production - 生产环境 */ function compressFrontend() { const rootDir = path.join(__dirname, "..") const sourceDir = path.join(rootDir, "dist") const outputDir = rootDir // 获取环境参数 const env = process.argv[2] if (!env || !["test", "production"].includes(env)) { console.error("❌ 错误: 请指定环境参数") console.error(" 用法: node scripts/compress.cjs ") console.error(" 示例: node scripts/compress.cjs test") console.error(" 示例: node scripts/compress.cjs production") process.exit(1) } // 从 package.json 读取版本号 const packageJsonPath = path.join(rootDir, "package.json") let version = "1.0.0" try { const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) version = packageJson.version || "1.0.0" } catch (error) { console.warn(`⚠️ 无法读取 package.json 版本号,使用默认版本: ${version}`) } // 检查源目录是否存在 if (!fs.existsSync(sourceDir)) { console.error("❌ 错误: 前端打包文件不存在") console.error(` 路径: ${sourceDir}`) console.error( ` 请先运行 pnpm build:${env === "test" ? "test" : ""} 构建前端项目`, ) process.exit(1) } // 删除之前的所有压缩包 console.log("🧹 清理旧的压缩包...\n") try { const files = fs.readdirSync(outputDir) const oldZipFiles = files.filter( (file) => file.startsWith("competition-web-") && file.endsWith(".tgz"), ) if (oldZipFiles.length > 0) { oldZipFiles.forEach((file) => { const filePath = path.join(outputDir, file) try { fs.unlinkSync(filePath) console.log(` ✅ 已删除: ${file}`) } catch (error) { console.warn(` ⚠️ 删除失败: ${file} - ${error.message}`) } }) console.log("") } else { console.log(" ℹ️ 没有找到旧的压缩包\n") } } catch (error) { console.warn(` ⚠️ 清理旧压缩包时出错: ${error.message}\n`) } // 生成文件名: competition-web-{env}-v{version}.tgz const zipFileName = `competition-web-${env}-v${version}.tgz` const zipFilePath = path.join(outputDir, zipFileName) console.log("📦 开始压缩前端打包文件...\n") console.log(` 环境: ${env}`) console.log(` 版本: v${version}`) console.log(` 源目录: ${sourceDir}`) console.log(` 输出文件: ${zipFilePath}\n`) try { // 使用相对路径,避免 Windows tar 路径问题 const tarCommand = `tar -czf "${zipFileName}" -C dist .` execSync(tarCommand, { cwd: rootDir, stdio: "inherit", shell: true, env: { ...process.env }, }) // 检查文件是否创建成功 if (fs.existsSync(zipFilePath)) { const stats = fs.statSync(zipFilePath) const fileSizeMB = (stats.size / (1024 * 1024)).toFixed(2) console.log(`\n✅ 压缩完成!`) console.log(` 文件: ${zipFileName}`) console.log(` 大小: ${fileSizeMB} MB`) console.log(` 路径: ${zipFilePath}`) } else { throw new Error("压缩文件未生成") } } catch (error) { console.error("\n❌ 压缩失败:", error.message) console.error("\n提示:") console.error(" 1. 确保已安装tar命令 (Windows 10+内置支持)") console.error(" 2. 确保有足够的磁盘空间") console.error(" 3. 确保输出目录有写入权限") process.exit(1) } } compressFrontend()