前端打包自动压缩为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'),
]
相关推荐
风骏时光牛马10 分钟前
用户管理模块接口开发
前端
彭亚川Allen32 分钟前
从零手搓 RAG 之检索全流程,给大模型接上自己的知识库
前端·后端·ai编程
IT_陈寒34 分钟前
别让Java字符串拼接偷偷吃掉你的内存
前端·人工智能·后端
软件技术NINI1 小时前
圣罗兰彩妆html+css 4页
前端·css·html
2601_951615202 小时前
网站模板 网站网页模板下载
前端·网络·html
酷炫码神2 小时前
Day 1|HTML5:一个商城首页的骨架,从 DOCTYPE 到语义化
前端·html·html5
AI源码3 小时前
鲜花商城(HTML 版)
前端·html
hiahiahia1233 小时前
Message 和对话
服务器·前端·数据库
溪语流沙3 小时前
【Web全栈进阶】Composition API与组件通信:props深入、emit、插槽
前端·css·vue.js
ZoeLandia3 小时前
TypeScript 03:泛型与工具类型
前端·typescript