安装filemanager-webpack-plugin插件
- npm install filemanager-webpack-plugin -D
- # or
- yarn add filemanager-webpack-plugin -D
在vue.config.js中配置
- # 引入filemanager-webpack-plugin
- const FileManagerPlugin = require('filemanager-webpack-plugin');
-
-
- # 在module.exports中配置
- configureWebpack: {
- plugins: [
- new FileManagerPlugin({
- events: {
- onEnd: {
- delete: [`./dist/*.zip`],
- archive: [
- {source: `./dist`, destination: `./dist/dist.zip`}
- ]
- }
- }
- })
- ]
- },
npm run build 或者 yarn run build打包即可
安装jszip
- npm install jszip -D
- # or
- yarn add jszip -D
新建 zip-compress.ts文件,放在和vite.config.ts同一级(js也可以)
- // zip-compress.ts
- import { resolve } from 'path'
- import fs from 'fs'
- import JSZip from 'jszip'
- const plugin = function (fileName = 'dist', output) {
- if (!output) output = resolve(__dirname, './dist')
- const fileZipName = fileName + '.zip'
- const makeZip = function () {
- const zip = new JSZip()
- const distPath = resolve(output)
- // 因为我想压缩包中的dist文件夹层级保留 且重新命名为dist 所以这里设置了allFolder ,如果不要该层级 则直接用zip即可
- let allFolder = zip.folder(fileName)
-
- const readDir = function (allFolder, dirPath) {
- // 读取dist下的根文件目录
- const files = fs.readdirSync(dirPath)
- files.forEach((fileName) => {
- const fillPath = `${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 = `${distPath}\\${fileZipName}`
- 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 = `${distPath}\\${fileZipName}`
- removeExistedZip()
- // 把zip包写到硬盘中,这个content现在是一段buffer
- fs.writeFileSync(dest, content)
- })
- }
- removeExistedZip()
- zipDir(distPath)
- }
- return {
- name: 'vite-plugin-auto-zip',
- apply: 'build',
- closeBundle() {
- makeZip()
- }
- }
- }
-
- export { plugin as default };
在vite.config.js中引入插件
- // 引入zip压缩插件
- import zipCompress from './zip-compress'
-
- // 在plugins中使用
-
- plugins: [
- vue(),
- zipCompress("fileName"),
- ...
- ],
npm run build 或者 yarn run build打包即可