zipDistPlugin.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import archiver from 'archiver';
  2. import { createWriteStream, existsSync } from 'fs';
  3. import { rm } from 'fs/promises';
  4. import { type RsbuildPlugin } from '@rsbuild/core';
  5. export function zipDistPlugin(distPath: string): RsbuildPlugin {
  6. return {
  7. name: 'zip-dist-plugin',
  8. setup(api) {
  9. api.onAfterBuild(async () => {
  10. // 从 process.env 获取环境信息
  11. const isProd = process.env.NODE_ENV === 'production';
  12. // 只在生产环境构建时打包
  13. if (!isProd) {
  14. return;
  15. }
  16. const zipPath = `${distPath}.zip`;
  17. console.log(`\n📦 正在打包 ${distPath} 为 ${zipPath}...`);
  18. // 检查目录是否存在
  19. if (!existsSync(distPath)) {
  20. console.error(`❌ 目录不存在: ${distPath}`);
  21. return;
  22. }
  23. return new Promise((resolve, reject) => {
  24. const output = createWriteStream(zipPath);
  25. const archive = archiver('zip', {
  26. zlib: { level: 9 } // 最高压缩级别
  27. });
  28. output.on('close', async () => {
  29. const MB = (archive.pointer() / 1024 / 1024).toFixed(2);
  30. console.log(`✅ 打包完成: ${zipPath} (${MB} MB)`);
  31. // 删除原始目录
  32. try {
  33. await rm(distPath, { recursive: true, force: true });
  34. console.log(`🗑️ 已删除原始目录: ${distPath}\n`);
  35. } catch (err) {
  36. console.error(`⚠️ 删除目录失败: ${distPath}`, err);
  37. }
  38. resolve();
  39. });
  40. archive.on('error', (err) => {
  41. console.error('❌ 打包失败:', err);
  42. reject(err);
  43. });
  44. archive.pipe(output);
  45. archive.directory(distPath, false);
  46. archive.finalize();
  47. });
  48. });
  49. }
  50. };
  51. }