zipBuildPlugin.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // zipPlugin.js
  2. import { resolve } from 'path';
  3. import { createWriteStream } from 'fs';
  4. import archiver from 'archiver';
  5. export default function zipBuildPlugin() {
  6. let outDir = 'dist'; // 默认值
  7. return {
  8. name: 'zip-after-build',
  9. configResolved(resolvedConfig) {
  10. // 读取 Vite 配置中的 build.outDir
  11. outDir = resolvedConfig.build.outDir;
  12. },
  13. closeBundle: {
  14. sequential: true,
  15. async handler() {
  16. const outputDir = resolve(__dirname, outDir);
  17. const zipFilePath = resolve(__dirname, `${outDir}.zip`);
  18. // 创建文件输出流
  19. const output = createWriteStream(zipFilePath);
  20. const archive = archiver('zip', {
  21. zlib: { level: 9 } // 设置压缩等级
  22. });
  23. return new Promise((resolve, reject) => {
  24. output.on('close', () => {
  25. console.log(`打包完成,共 ${archive.pointer()} 字节`);
  26. resolve();
  27. });
  28. archive.on('warning', (err) => {
  29. if (err.code !== 'ENOENT') {
  30. reject(err);
  31. }
  32. });
  33. archive.on('error', (err) => {
  34. reject(err);
  35. });
  36. // 将归档数据管道化到文件
  37. archive.pipe(output);
  38. // 将 dist 文件夹及其内容都压缩进 zip
  39. archive.directory(outputDir, outDir);
  40. // 完成归档
  41. archive.finalize();
  42. });
  43. }
  44. }
  45. };
  46. }