Newer
Older
DH_Apicture / vite / plugins / buildZip.js
@zhangqy zhangqy on 29 Nov 1 KB first commit
  1. // 直接打包成zip包
  2.  
  3. const pluginZip = function (fileName = 'WaterBrain', output) {
  4. const path = require('path');
  5. if (!output) output = path.resolve(__dirname, './../../WaterBrain');
  6. fileName += '.zip';
  7. const makeZip = function () {
  8. const path = require('path');
  9. const fs = require('fs');
  10. const JSZip = require('jszip');
  11. const zip = new JSZip();
  12. const distPath = path.resolve(output);
  13. const readDir = function (zip, dirPath) {
  14. // 读取dist下的根文件目录
  15. const files = fs.readdirSync(dirPath);
  16. files.forEach(fileName => {
  17. const fillPath = path.join(dirPath, './', fileName);
  18. const file = fs.statSync(fillPath);
  19. // 如果是文件夹的话需要递归遍历下面的子文件
  20. if (file.isDirectory()) {
  21. const dirZip = zip.folder(fileName);
  22. readDir(dirZip, fillPath);
  23. } else {
  24. // 读取每个文件为buffer存到zip中
  25. zip.file(fileName, fs.readFileSync(fillPath));
  26. }
  27. });
  28. };
  29. const removeExistedZip = () => {
  30. const dest = path.join(distPath, './' + fileName);
  31. if (fs.existsSync(dest)) {
  32. fs.unlinkSync(dest);
  33. }
  34. };
  35. const zipDir = function () {
  36. readDir(zip, distPath);
  37. zip
  38. .generateAsync({
  39. type: 'nodebuffer', // 压缩类型
  40. compression: 'DEFLATE', // 压缩算法
  41. compressionOptions: {
  42. // 压缩级别
  43. level: 9,
  44. },
  45. })
  46. .then(content => {
  47. const dest = path.join(distPath, '../' + fileName);
  48. removeExistedZip();
  49. // 把zip包写到硬盘中,这个content现在是一段buffer
  50. fs.writeFileSync(dest, content);
  51. });
  52. };
  53. removeExistedZip();
  54. zipDir(distPath);
  55. };
  56. return {
  57. name: 'vite-plugin-auto-zip',
  58. apply: 'build',
  59. closeBundle() {
  60. makeZip();
  61. },
  62. };
  63. };
  64. module.exports = pluginZip;