1.使用 npm i jszip -D 安装依赖
2.根目录创建craeteZip.ts文件
// zip.js 打包自动生成zip包,需npm i jszip -D
const plugin = function(fileName = 'dist', output:any){
const path = require('path');
if(!output)output = path.resolve(__dirname,'./dist');//./distTest是根据实际路径而来
fileName += '.zip';
const makeZip = function () {
const path = require('path')
const fs = require('fs')
const JSZip = require('jszip');
const zip = new JSZip()
const distPath:any = path.resolve(output)
const readDir = function (zip:any, dirPath:string) {
// 读取dist下的根文件目录
const files = fs.readdirSync(dirPath);
files.forEach((fileName:string) => {
const fillPath = path.join(dirPath, "./", fileName)
const file = fs.statSync(fillPath);
// 如果是文件夹的话需要递归遍历下面的子文件
if (file.isDirectory()) {
const dirZip = zip.folder(fileName);
readDir(dirZip, fillPath);
} else {
// 读取每个文件为buffer存到zip中
zip.file(fileName, fs.readFileSync(fillPath))
}
});
}
const removeExistedZip = () => {
const dest = path.join(distPath, './' + fileName)
if (fs.existsSync(dest)) {
fs.unlinkSync(dest)
}
}
const zipDir = function () {
const distZip = zip.folder('dist');
readDir(distZip, distPath);
zip.generateAsync({
type: "nodebuffer", // 压缩类型
compression: "DEFLATE", // 压缩算法
compressionOptions: { // 压缩级别
level: 9
}
}).then((content:any) => {
const dest = path.join(distPath, '../' + fileName)
removeExistedZip()
// 把zip包写到硬盘中,这个content现在是一段buffer
fs.writeFileSync(dest, content);
});
}
removeExistedZip()
zipDir()
}
return {
name: 'vite-plugin-auto-zip',
apply: 'build',
closeBundle(){
makeZip()
}
}
}
module.exports = plugin
3.在vite.config.ts 中的 plugins 中引入使用即可
import createZip from "./createZip"
........
plugins: [
createZip()
],
// 其他 Vite 配置项