vue3.0 + vite打包完成后,将dist下的资源包打包成zip的两种方法

vue3.0 + vite打包完成之后,自动将dist下的资源包打包成zip

1、vite-plugin-zip-pack 插件

安装插件

bash 复制代码
npm i -D vite-plugin-zip-pack

修改vite.config.ts,增加plugin

ts 复制代码
// vite.config.ts
import { defineConfig } from "vite";
import zipPack, { Options as ZipPickOptions } from "vite-plugin-zip-pack";

export default defineConfig(({ mode, command }) => {
    // mode => vite 提供的用于区分环境的变量,可以通过在 script 命令中修改 --mode [模式名] 设置
    // command => vite 提供的用于区分命令的变量,值为: 'build' | 'serve'
    
    const zipPickOptions: ZipPickOptions = {
        inDir: `dist`, // 生成的web包根目录
        outFileName: `dist-${mode}.zip` // 生成zip的名称,可自定义
    }
    
    return {
        plugins: [zipPack(zipPickOptions)],
        build: {
          outDir: 'dist'
        },
    }
})

2、执行生成app_config.js脚本之后打包

bash 复制代码
# 安装依赖环境
npm i -D @types/archiver
npm i -D archiver
npm i -D @types/fs-extra
npm i -D fs-extra
npm i -D dayjs
bash 复制代码
import fs from 'fs-extra';
import archiver from 'archiver';
import pkg from '../../package.json';
import dayjs from 'dayjs';

/**
 * 获取用户根目录
 * @param dir file path
 */
export function getRootPath(...dir: string[]) {
  return path.resolve(process.cwd(), ...dir);
}

/**
 * 将dist目录下的文件构建成zip包,并移动到dist下;
 */
export const buildZipPackage = async () => {
  const OUTPUT_DIR = 'dist';
  console.log(`✨ [${pkg.name}]` + ' - 文件打包开始...');
  // 设置输出ZIP文件的路径和文件名
  const filePath = `${OUTPUT_DIR}/`;
  const fileName = `${pkg.name}-${pkg.version}-${dayjs().format('YYYYMMDDHH')}.zip`;
  const outputFilePath = getRootPath(fileName);

  // 创建文件输出流
  const output = fs.createWriteStream(outputFilePath);
  const archive = archiver('zip', {
    zlib: { level: 9 }, // 压缩级别
  });

  // 监听输出流关闭事件
  output.on('close', function () {
    const size = 1024;
    const fileSize = archive.pointer();
    let prinfSize = fileSize.toFixed(1);
    let unit = 'B';
    if (fileSize > size * size) {
      unit = 'M';
      prinfSize = (fileSize / (size * size)).toFixed(1);
    } else if (fileSize > size) {
      unit = 'K';
      prinfSize = (fileSize / size).toFixed(1);
    }
    console.log(`✨ [${fileName}] - 构建成功,总大小: ${prinfSize} ${unit}!`);

    const destinationPath = getRootPath(`dist/${fileName}`);
    // 移动文件
    fs.rename(outputFilePath, destinationPath, (err) => {
      if (err) throw err;
      console.log(`✨ [${fileName}] - 文件已被移动到:`, [OUTPUT_DIR]);
    });
    console.log(`✨ [${pkg.name}]` + ' - 文件打包完成.');
  });

  // 监听压缩过程中的警告
  archive.on('warning', function (err) {
    if (err.code === 'ENOENT') {
      // log warning
    } else {
      // 抛出错误
      throw err;
    }
  });

  // 监听压缩过程中的错误
  archive.on('error', function (err) {
    throw err;
  });

  // 将输出流与存档关联起来
  archive.pipe(output);

  // 添加dist目录下的所有文件到压缩包
  archive.directory(getRootPath(filePath), false);

  // 完成压缩
  archive.finalize();
};

buildZipPackage();

测试:

bash 复制代码
# 测试命令行
yarn esno ./buildZipPackage.ts

# 执行结果如下:
✨ [gx-portal] - 文件打包开始...
✨ [gx-portal-2.0.0-2024102322.zip] - 构建成功,总大小: 5.0 M!
✨ [gx-portal] - 文件打包完成.
✨ [gx-portal-2.0.0-2024102322.zip] - 文件已被移动到: [ 'dist' ]
相关推荐
Vicky&James10 分钟前
WPF到Web的无缝过渡:英雄联盟客户端项目OpenSilver迁移实战
前端·wpf
m0_7482336414 分钟前
RabbitMQ 进阶
android·前端·后端
不想有bug的小菜鸟22 分钟前
vue3使用iframe全屏展示pdf效果
前端·pdf
m0_7482386323 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
u01005596024 分钟前
前端代理,解决跨域问题讲解
前端
quitv29 分钟前
react脚手架配置别名
前端·javascript·react.js
m0_5287238138 分钟前
前端如何进行性能优化
前端·性能优化
化作繁星39 分钟前
在 Vue 3 中,如何缓存和复用动态组件
前端·vue.js·缓存
一粒沙-1 小时前
iOS 将GIF图分享至微信
前端·ios
graywen1 小时前
从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
前端