Vite项目打包生成dist.zip方法

使用自定义插件(推荐)

步骤1:安装依赖

bash

复制

复制代码
npm install jszip -D

步骤2:创建插件文件

在项目根目录新建zip.js(或createZip.ts,若使用TypeScript),写入以下代码:

javascript

复制

ini 复制代码
const path = require('path');
const fs = require('fs');
const JSZip = require('jszip');

const plugin = (fileName = 'dist', outputPath) => {
  const output = outputPath || path.resolve(__dirname, './dist');
  fileName += '.zip';

  const makeZip = () => {
    const zip = new JSZip();
    const distPath = path.resolve(output);

    // 递归读取文件夹并添加到Zip
    const readDir = (zipInstance, dirPath) => {
      const files = fs.readdirSync(dirPath);
      files.forEach(file => {
        const filePath = path.join(dirPath, file);
        const stats = fs.statSync(filePath);
        if (stats.isDirectory()) {
          const folder = zipInstance.folder(file);
          readDir(folder, filePath);
        } else {
          zipInstance.file(file, fs.readFileSync(filePath));
        }
      });
    };

    // 删除已存在的Zip文件
    const removeExistingZip = () => {
      const zipPath = path.join(distPath, '../', fileName);
      if (fs.existsSync(zipPath)) fs.unlinkSync(zipPath);
    };

    // 生成Zip内容并写入文件
    readDir(zip, distPath);
    zip.generateAsync({
      type: 'nodebuffer',
      compression: 'DEFLATE',
      compressionOptions: { level: 9 }
    }).then(content => {
      const destPath = path.join(distPath, '../', fileName);
      removeExistingZip();
      fs.writeFileSync(destPath, content);
    });
  };

  return {
    name: 'vite-plugin-auto-zip',
    apply: 'build',
    closeBundle: makeZip
  };
};

module.exports = plugin;

步骤3:在Vite配置中引入插件

修改vite.config.js(或vite.config.ts):

javascript

复制

javascript 复制代码
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import zipPlugin from './zip';

export default defineConfig({
  plugins: [
    vue(),
    zipPlugin() // 可传参自定义文件名,如 zipPlugin('myapp', './custom-dist')
  ],
  build: {
    outDir: 'dist', // 可选:修改输出目录名:cite[3]:cite[8]
  }
});

步骤4:执行打包

bash

复制

arduino 复制代码
npm run build

如果只想在开发环境development)下启用 ZIP 打包功能,而在生产环境production)下禁用,可以修改 Vite 插件逻辑,使其仅在 vite devvite build --mode development 时生效。以下是具体实现方法:


方法 1:基于 mode 动态启用插件

1. 修改插件逻辑(createZip.js

javascript

复制

ini 复制代码
import path from 'path';
import fs from 'fs';
import JSZip from 'jszip';

export default function createZipPlugin(options = {}) {
  const {
    fileName = 'dist',
    outputPath,
    enabled = process.env.NODE_ENV === 'development' // 默认开发环境启用
  } = options;

  if (!enabled) {
    // 如果禁用,返回一个空插件
    return {
      name: 'vite-plugin-auto-zip',
      apply: 'build',
      closeBundle: () => {} // 空函数
    };
  }

  const output = outputPath || path.resolve(process.cwd(), './dist');
  const zipFileName = `${fileName}.zip`;

  const makeZip = () => {
    const zip = new JSZip();
    const distPath = path.resolve(output);

    // 递归读取文件夹
    const readDir = (zipInstance, dirPath) => {
      const files = fs.readdirSync(dirPath);
      files.forEach(file => {
        const filePath = path.join(dirPath, file);
        const stats = fs.statSync(filePath);
        if (stats.isDirectory()) {
          const folder = zipInstance.folder(file);
          readDir(folder, filePath);
        } else {
          zipInstance.file(file, fs.readFileSync(filePath));
        }
      });
    };

    // 生成 ZIP
    readDir(zip, distPath);
    zip.generateAsync({
      type: 'nodebuffer',
      compression: 'DEFLATE',
      compressionOptions: { level: 9 }
    }).then(content => {
      const destPath = path.join(distPath, '../', zipFileName);
      if (fs.existsSync(destPath)) fs.unlinkSync(destPath);
      fs.writeFileSync(destPath, content);
    });
  };

  return {
    name: 'vite-plugin-auto-zip',
    apply: 'build',
    closeBundle: makeZip
  };
}

2. 在 vite.config.js 中动态配置

javascript

复制

javascript 复制代码
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import createZipPlugin from './createZip';

export default defineConfig(({ mode }) => ({
  plugins: [
    vue(),
    createZipPlugin({
      enabled: mode === 'development' // 仅开发模式启用
    })
  ],
  build: {
    outDir: 'dist'
  }
}));
相关推荐
江号软件分享37 分钟前
有效保障隐私,如何安全地擦除电脑上的敏感数据
前端
web守墓人2 小时前
【前端】ikun-markdown: 纯js实现markdown到富文本html的转换库
前端·javascript·html
Savior`L2 小时前
CSS知识复习5
前端·css
许白掰2 小时前
Linux入门篇学习——Linux 工具之 make 工具和 makefile 文件
linux·运维·服务器·前端·学习·编辑器
中微子6 小时前
🔥 React Context 面试必考!从源码到实战的完整攻略 | 99%的人都不知道的性能陷阱
前端·react.js
中微子7 小时前
React 状态管理 源码深度解析
前端·react.js
加减法原则8 小时前
Vue3 组合式函数:让你的代码复用如丝般顺滑
前端·vue.js
yanlele9 小时前
我用爬虫抓取了 25 年 6 月掘金热门面试文章
前端·javascript·面试
lichenyang4539 小时前
React移动端开发项目优化
前端·react.js·前端框架
你的人类朋友9 小时前
🍃Kubernetes(k8s)核心概念一览
前端·后端·自动化运维