前端打包自动压缩为zip--archiver

安装依赖

shell 复制代码
pnpm add archiver @types/archiver

/vitePlugins/autoBuildZip.ts

ts 复制代码
import { Plugin } from 'vite';
import archiver from 'archiver';
import fs from 'fs';

const compressFolder = (folderPath: string, outputFilePath: string) => {
  const output = fs.createWriteStream(`${__dirname}/../${outputFilePath}.zip`);
  const archive = archiver('zip', {
    zlib: { level: 9 },
  });

  output.on('close', function () {
    const size = (archive.pointer() / 1024 / 1024).toFixed(2);
    console.log(`
          ----------------------------------------------------------
          ------                  压缩完成                    ------
          ------ 文件路径:项目根目录:${outputFilePath}.zip     ------
          ------               文件大小${size}M                  ------
          ----------------------------------------------------------
      `);
  });

  archive.on('warning', function (err: { code: string }) {
    if (err.code === 'ENOENT') {
    } else {
      throw err;
    }
  });

  archive.on('error', function (err: any) {
    throw err;
  });
  archive.pipe(output);
  archive.directory(folderPath, outputFilePath);
  archive.finalize();
};

export default function autoBuildZip(fileName: string): Plugin {
  return {
    name: 'vite:autoBuildZip',
    apply: 'build',
    enforce: 'post',
    closeBundle() {
      compressFolder(fileName, fileName);
    },
  };
}

使用

vite.config.ts中引入

ts 复制代码
// 该插件用于自动打包zip文件
import autoBuildZip from './vitePlugins/autoBuildZip';

plugins:[
	autoBuildZip('dist'),
]
相关推荐
程序员buddha1 分钟前
ES6 迭代器与生成器
前端·javascript·es6
周周记笔记13 分钟前
初识HTML和CSS(一)
前端·css·html
chxii1 小时前
在 IIS 中实现 SSL 证书的自动续期
前端
周星星日记1 小时前
vue3中静态提升和patchflag实现
前端·vue.js·面试
橘子编程1 小时前
React 19 全栈开发实战指南
前端·react.js·前端框架
DanCheOo1 小时前
AI Streaming 架构:从浏览器到服务端的全链路流式设计
前端·agent
我是小趴菜1 小时前
前端如何让图片、视频、pdf等文件在浏览器直接下载而非预览
前端
cg331 小时前
开源项目自动化:用 GitHub Actions 让每个 Issue 都被温柔以待
前端
haierccc1 小时前
Win7、2008R2、Win10、Win11使用FLASH的方法
前端·javascript·html
We་ct1 小时前
LeetCode 50. Pow(x, n):从暴力法到快速幂的优化之路
开发语言·前端·javascript·算法·leetcode·typescript·