vue3+vite打包自动生成dist.zip压缩包

本文介绍如何使用Vue3和Vite构建项目时,通过自定义插件实现自动将dist文件夹内容打包成ZIP文件。该插件利用Node.js内置模块和第三方库JSZip完成文件读取、压缩及写入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先写个生成zip的功能。新建一个zip.js文件,放在和vite.config.js同一级

//  zip.js
const plugin = function(fileName = 'dist', output){
    const path = require('path');            
    if(!output)output = path.resolve(__dirname,'./dist');
    fileName += '.zip';
    const makeZip = function () {
        const path = require('path')
        const fs = require('fs')
        const JSZip = require('jszip');
        const zip = new JSZip()
        const distPath = path.resolve(output)
        const readDir = function (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 = function () {
            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()
        }
    }
}
module.exports = plugin

在vite.config.js中引入插件

//  vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from "path";
import myPlugin from './zip'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
    vue(),
    myPlugin()
  ],
  resolve: {
    alias: {
      "@": path.resolve(__dirname, "src"),
    },
  },
})

这样就大功告成了

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夕阳_醉了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值