2024-05-28 10:22:20 +08:00
|
|
|
|
import type { Plugin } from 'vite';
|
|
|
|
|
import { isArray } from '@pureadmin/utils';
|
|
|
|
|
import compressPlugin from 'vite-plugin-compression';
|
|
|
|
|
|
2024-07-03 19:44:04 +08:00
|
|
|
|
export const configCompressPlugin = (compress: any): Plugin | Plugin[] | null => {
|
|
|
|
|
if (compress === 'none' || compress === void 0) return null;
|
2024-05-28 10:22:20 +08:00
|
|
|
|
|
|
|
|
|
const gz = {
|
|
|
|
|
// 生成的压缩包后缀
|
|
|
|
|
ext: '.gz',
|
|
|
|
|
// 体积大于threshold才会被压缩
|
|
|
|
|
threshold: 0,
|
|
|
|
|
// 默认压缩.js|mjs|json|css|html后缀文件,设置成true,压缩全部文件
|
|
|
|
|
filter: () => true,
|
|
|
|
|
// 压缩后是否删除原始文件
|
|
|
|
|
deleteOriginFile: false,
|
|
|
|
|
};
|
|
|
|
|
const br = {
|
|
|
|
|
ext: '.br',
|
|
|
|
|
algorithm: 'brotliCompress',
|
|
|
|
|
threshold: 0,
|
|
|
|
|
filter: () => true,
|
|
|
|
|
deleteOriginFile: false,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const codeList = [
|
|
|
|
|
{ k: 'gzip', v: gz },
|
|
|
|
|
{ k: 'brotli', v: br },
|
|
|
|
|
{ k: 'both', v: [gz, br] },
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
const plugins: Plugin[] = [];
|
|
|
|
|
|
|
|
|
|
codeList.forEach(item => {
|
|
|
|
|
if (compress.includes(item.k)) {
|
|
|
|
|
if (compress.includes('clear')) {
|
|
|
|
|
if (isArray(item.v)) {
|
|
|
|
|
item.v.forEach(vItem => {
|
|
|
|
|
plugins.push(compressPlugin(Object.assign(vItem, { deleteOriginFile: true })));
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
plugins.push(compressPlugin(Object.assign(item.v, { deleteOriginFile: true })));
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
if (isArray(item.v)) {
|
|
|
|
|
item.v.forEach(vItem => {
|
|
|
|
|
plugins.push(compressPlugin(vItem));
|
|
|
|
|
});
|
|
|
|
|
} else {
|
|
|
|
|
plugins.push(compressPlugin(item.v));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return plugins;
|
|
|
|
|
};
|