前端打包自动压缩为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'),
]
相关推荐
许商1 分钟前
【stm32】【printf】
java·前端·stm32
JIngJaneIL11 分钟前
智慧物业|物业管理|基于SprinBoot+vue的智慧物业管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·论文·智慧物业管理系统
爬坑的小白14 分钟前
vue 2.0 路由跳转时新开tab
前端·javascript·vue.js
爬坑的小白14 分钟前
vue x 状态管理
前端·javascript·vue.js
凌览28 分钟前
一键去水印|5 款免费小红书解析工具推荐
前端·javascript·后端
lichong95132 分钟前
鸿蒙 web组件开发
前端·typescript
1024小神33 分钟前
在html中使用js动态交换两个元素的位置
前端
鹿鹿鹿鹿isNotDefined34 分钟前
逐步手写,实现符合 Promise A+ 规范的 Promise
前端·javascript·算法
一千柯橘34 分钟前
Electron - IPC 解决主进程和渲染进程之间的通信
前端
申阳35 分钟前
Day 16:02. 基于 Tauri 2.0 开发后台管理系统-项目初始化配置
前端·后端·程序员