zipBuildPlugin.js 1.3 KB

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