compress.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { isArray } from 'lodash-es';
  2. import compressPlugin from 'vite-plugin-compression';
  3. import type { Plugin } from 'vite';
  4. export const configCompressPlugin = (compress: BuildCompression): Plugin | Plugin[] | null => {
  5. if (compress === 'none') return null;
  6. // framework 模式下 Vite 分 client / ssr 两个环境构建;ssr:false 时 react-router 会删除 dist/server,
  7. // 压缩插件若在 server 环境的 closeBundle 阶段扫描已被删的目录会报 ENOENT。故只对 client 环境启用压缩
  8. //(server 产物本就不部署,无需压缩)。
  9. const onlyClient = (plugin: Plugin): Plugin => ({
  10. ...plugin,
  11. applyToEnvironment: (environment) => environment.name === 'client',
  12. });
  13. const gz = {
  14. // 生成的压缩包后缀
  15. ext: '.gz',
  16. // 体积大于threshold才会被压缩
  17. threshold: 0,
  18. // 默认压缩.js|mjs|json|css|html后缀文件,设置成true,压缩全部文件
  19. filter: () => true,
  20. // 压缩后是否删除原始文件
  21. deleteOriginFile: false,
  22. // 是否打印详细信息
  23. verbose: false,
  24. };
  25. const br = {
  26. ext: '.br',
  27. algorithm: 'brotliCompress',
  28. threshold: 0,
  29. filter: () => true,
  30. deleteOriginFile: false,
  31. verbose: false,
  32. };
  33. const codeList = [
  34. { k: 'gzip', v: gz },
  35. { k: 'brotli', v: br },
  36. { k: 'both', v: [gz, br] },
  37. ];
  38. const plugins: Plugin[] = [];
  39. codeList.forEach((item) => {
  40. if (compress.includes(item.k)) {
  41. if (compress.includes('clear')) {
  42. if (isArray(item.v)) {
  43. item.v.forEach((vItem) => {
  44. plugins.push(
  45. onlyClient(
  46. compressPlugin(Object.assign(vItem, { deleteOriginFile: true }))
  47. )
  48. );
  49. });
  50. } else {
  51. plugins.push(
  52. onlyClient(
  53. compressPlugin(Object.assign(item.v, { deleteOriginFile: true }))
  54. )
  55. );
  56. }
  57. } else {
  58. if (isArray(item.v)) {
  59. item.v.forEach((vItem) => {
  60. plugins.push(onlyClient(compressPlugin(vItem)));
  61. });
  62. } else {
  63. plugins.push(onlyClient(compressPlugin(item.v)));
  64. }
  65. }
  66. }
  67. });
  68. return plugins;
  69. };