compress.ts 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import type { Plugin } from "vite";
  2. import { isArray } from "@pureadmin/utils";
  3. import compressPlugin from "vite-plugin-compression";
  4. export const configCompressPlugin = (
  5. compress: ViteCompression
  6. ): Plugin | Plugin[] => {
  7. if (compress === "none") return null;
  8. const gz = {
  9. // 生成的压缩包后缀
  10. ext: ".gz",
  11. // 体积大于threshold才会被压缩
  12. threshold: 0,
  13. // 默认压缩.js|mjs|json|css|html后缀文件,设置成true,压缩全部文件
  14. filter: () => true,
  15. // 压缩后是否删除原始文件
  16. deleteOriginFile: false
  17. };
  18. const br = {
  19. ext: ".br",
  20. algorithm: "brotliCompress",
  21. threshold: 0,
  22. filter: () => true,
  23. deleteOriginFile: false
  24. };
  25. const codeList = [
  26. { k: "gzip", v: gz },
  27. { k: "brotli", v: br },
  28. { k: "both", v: [gz, br] }
  29. ];
  30. const plugins: Plugin[] = [];
  31. codeList.forEach(item => {
  32. if (compress.includes(item.k)) {
  33. if (compress.includes("clear")) {
  34. if (isArray(item.v)) {
  35. item.v.forEach(vItem => {
  36. plugins.push(
  37. compressPlugin(Object.assign(vItem, { deleteOriginFile: true }))
  38. );
  39. });
  40. } else {
  41. plugins.push(
  42. compressPlugin(Object.assign(item.v, { deleteOriginFile: true }))
  43. );
  44. }
  45. } else {
  46. if (isArray(item.v)) {
  47. item.v.forEach(vItem => {
  48. plugins.push(compressPlugin(vItem));
  49. });
  50. } else {
  51. plugins.push(compressPlugin(item.v));
  52. }
  53. }
  54. }
  55. });
  56. return plugins;
  57. };