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' ]
相关推荐
邝邝邝邝丹14 分钟前
React学习———React Router
前端·学习·react.js
Yvonne爱编码39 分钟前
CSS- 2.1 实战之图文混排、表格、表单
前端·css·html·github·状态模式·html5·hbuilder
前端小巷子42 分钟前
CSS面试题汇总
前端·css·面试
绝美焦栖1 小时前
vue复杂数据类型多层嵌套的监听
前端·javascript·vue.js
GoodStudyAndDayDayUp1 小时前
gitlab+portainer 实现Ruoyi Vue后端CI/CD
vue.js·ci/cd·gitlab
xixixin_2 小时前
【Vite】前端开发服务器的配置
服务器·前端·网络
.生产的驴2 小时前
Vue3 加快页面加载速度 使用CDN外部库的加载 提升页面打开速度 服务器分发
运维·服务器·前端·vue.js·分布式·前端框架·vue
史迪仔01122 小时前
Python生成器:高效处理大数据的秘密武器
前端·数据库·python
蓝婷儿3 小时前
前端面试每日三题 - Day 34
前端·面试·职场和发展
CopyLower3 小时前
苹果计划将AI搜索集成至Safari:谷歌搜索下降引发的市场变革
前端·人工智能·safari