pms-front/public/js/zip.js

76 lines
2.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/*
* @FilePath : /public/js/zip.js
* @Description :
*/
/*
* @Author: suhang suhang_max@163.com
* @Date: 2023-06-01 00:14:29
* @LastEditors: suhang suhang_max@163.com
* @LastEditTime: 2023-06-01 10:56:19
* @FilePath: \train-assessd:\Code\basic-frontend\zip.js
* @Description: 将打包后的文件夹自动压缩成zip
*/
// console.log(import.meta, 'import.meta.env.VITE_APP_GISURL')
import path from 'path'
import fs from 'fs'
import JSZip from 'jszip'
const plugin = (fileName = 'pms-front', output) => {
// if (!output) output = path.resolve(__dirname, `../..${import.meta.env.VITE_BASE_URL}`)
output = path.resolve(__dirname, `../..${output}`)
fileName += '.zip'
const makeZip = () => {
const zip = new JSZip()
const distPath = path.resolve(output)
const readDir = (zip, 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 = 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 = () => {
readDir(zip, 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