前端打包自动压缩为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'),
]
相关推荐
3824278271 天前
JS表单提交:submit事件的关键技巧与注意事项
前端·javascript·okhttp
Kagol1 天前
深入浅出 TinyEditor 富文本编辑器系列2:快速开始
前端·typescript·开源
小二·1 天前
Python Web 开发进阶实战:Flask-Login 用户认证与权限管理 —— 构建多用户待办事项系统
前端·python·flask
浩瀚之水_csdn1 天前
python字符串解析
前端·数据库·python
全栈小51 天前
【前端】在JavaScript中,=、==和===是三种不同的操作符,用途和含义完全不同,一起瞧瞧
开发语言·前端·javascript
如果你好1 天前
Vue createRenderer 自定义渲染器从入门到实战
前端·javascript·vue.js
温宇飞1 天前
Web 图形合成技术:Blending 与 Porter-Duff Compositing
前端
小高0071 天前
读懂 Tailwind v4:为什么它是现代前端项目的必选项?
前端·javascript·vue.js
我的golang之路果然有问题1 天前
python中 unicorn 热重启问题和 debug 的 json
java·服务器·前端·python·json
SpringLament1 天前
从零打造AI智能博客:一个项目带你入门全栈与大模型应用开发
前端·aigc