代码拉取完成,页面将自动刷新
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
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。