加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
zip.js 2.05 KB
一键复制 编辑 原始数据 按行查看 历史
杨智文 提交于 2023-02-14 14:46 . init
import path from 'path'
import fs from 'fs'
import JSZip from 'jszip'
// zip.js
const plugin = function (fileName = 'product_h5', output) {
if (!output) output = path.resolve(__dirname, './dist')
fileName += '.zip'
const makeZip = function () {
const zip = new JSZip()
const distPath = path.resolve(output)
// 因为我想压缩包中的dist文件夹层级保留 且重新命名为 product_h5 所以这里设置了allFolder ,如果不要该层级 则直接用zip即可
// let allFolder = zip.folder('product_h5')
let allFolder = zip
const readDir = function (allFolder, dirPath) {
// 读取dist下的根文件目录
const files = fs.readdirSync(dirPath)
files.forEach((fileName) => {
const fillPath = path.join(dirPath, './', fileName)
const file = fs.statSync(fillPath)
// 如果是文件夹的话需要递归遍历下面的子文件
if (file.isDirectory()) {
const dirZip = allFolder.folder(fileName)
readDir(dirZip, fillPath)
} else {
// 读取每个文件为buffer存到zip中
allFolder.file(fileName, fs.readFileSync(fillPath))
}
})
}
const removeExistedZip = () => {
const dest = path.join(distPath, './' + fileName)
if (fs.existsSync(dest)) {
fs.unlinkSync(dest)
}
}
const zipDir = function () {
readDir(allFolder, distPath)
zip
.generateAsync({
type: 'nodebuffer', // 压缩类型
compression: 'DEFLATE', // 压缩算法
compressionOptions: {
// 压缩级别
level: 9
}
})
.then((content) => {
const dest = path.join(distPath, '../' + fileName)
removeExistedZip()
// 把zip包写到硬盘中,这个content现在是一段buffer
fs.writeFileSync(dest, content)
})
}
removeExistedZip()
zipDir(distPath)
}
return {
name: 'vite-plugin-auto-zip',
apply: 'build',
closeBundle() {
makeZip()
}
}
}
export default plugin
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化