第一步:先安装插件 npm i jszip -D
npm i jszip -D
npm i vite-plugin-compression -D
第二步:在根目录下面创建一个zip.js文件(和vite.config.js同一级)
// eslint-disable-next-line func-names
const plugin = function (fileName = 'yunyingfenxi_2023', output) {const path = require('path')if (!output) output = path.resolve(__dirname, './yunyingfenxi_2023') // ./distTest是根据实际路径而来fileName += '.zip'const makeZip = function () {const path = require('path')const fs = require('fs')const JSZip = require('jszip')const zip = new JSZip()const distPath = path.resolve(output)const readDir = function (zip, dirPath) {// 读取dist下的根文件目录const files = fs.readdirSync(dirPath)files.forEach((fileName) => {const fillPath = path.join(dirPath, './', fileName)const file = fs.statSync(fillPath)// 如果是文件夹的话需要递归遍历下面的子文件if (file.isDirectory()) {const dirZip = zip.folder(fileName)readDir(dirZip, fillPath)} else {// 读取每个文件为buffer存到zip中zip.file(fileName, fs.readFileSync(fillPath))}})}const removeExistedZip = () => {const dest = path.join(distPath, `./${fileName}`)if (fs.existsSync(dest)) {fs.unlinkSync(dest)}}const zipDir = function () {readDir(zip, distPath)zip.generateAsync({type: 'nodebuffer', // 压缩类型compression: 'DEFLATE', // 压缩算法compressionOptions: {// 压缩级别level: 9,},}).then((content) => {const dest = path.join(distPath, `../${fileName}`)removeExistedZip()// 把zip包写到硬盘中,这个content现在是一段bufferfs.writeFileSync(dest, content)})}removeExistedZip()zipDir(distPath)}return {name: 'vite-plugin-auto-zip',apply: 'build',closeBundle() {makeZip()},}
}
module.exports = plugin
第三步:在vite.config.js中引入插件
import { fileURLToPath, URL } from 'node:url'import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import eslintPlugin from 'vite-plugin-eslint'
import viteCompression from 'vite-plugin-compression'
import myPlugin from './zip'// https://vitejs.dev/config/
export default defineConfig({plugins: [vue(),myPlugin(),viteCompression({threshold: 1024 * 500, // 对大于500kb的文件进行压缩algorithm: 'gzip', // 采用的压缩算法,默认是 gzipext: '.gz', // 生成的压缩包后缀}),eslintPlugin({cache: true,}),],resolve: {alias: {'@': fileURLToPath(new URL('./src', import.meta.url)),},},base: './',build: {sourcemap: false,outDir: 'yunyingfenxi_2023',rollupOptions: {output: {chunkFileNames: 'assets/js/[name]-[hash].js',entryFileNames: 'assets/jsEntry/[name]-[hash].js', // html引入的js文件assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',},brotliSize: true, // 不统计target: 'esnext',minify: 'esbuild', // 混淆器,terser构建后文件体积更小},},
})