vite插件-打包完成后压缩成zip并上传oss
js
import { Plugin } from "vite";
import OSS from "ali-oss";//阿里云oss
import path from "path";
import archiver from "archiver";
import fs from "fs";
const client = new OSS({
region: "", // 示例:'oss-cn-hangzhou',填写Bucket所在地域。
accessKeyId: "", // 设置OSS_ACCESS_KEY_ID。
accessKeySecret: "", // 设置OSS_ACCESS_KEY_SECRET。
bucket: "", // 填写存储空间名称。
});
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 ------
------ 准备上传至oss ------
----------------------------------------------------------
`);
client
.put(
`/app2/zhong-ning/${folderPath}.zip`,
path.normalize(`${__dirname}/../${folderPath}.zip`)
)
.then((res) => {
const url = `https://njbx-dev-gyl.oss-cn-zhangjiakou.aliyuncs.com/app2/zhong-ning/${folderPath}.zip`;
console.log(`
----------------------------------------------------------
------ 上传成功 ------
地址:${url}
----------------------------------------------------------
`);
});
});
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 autoUploadZip(fileName: string): Plugin {
return {
name: "vite:autoUploadZip",
apply: "build",
enforce: "post",
closeBundle() {
compressFolder(fileName, fileName);
},
};
}
使用
js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
mport autoUploadZip from './vite-plugins/autoUploadZip.ts'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), autoUploadZip('打包文件夹名称')],
})
//控制台使出
✓ built in 18.30s
----------------------------------------------------------
------ 压缩完成 ------
------ 文件路径:项目根目录:**.zip ------
------ 文件大小***M ------
------ 准备上传至oss ------
----------------------------------------------------------
----------------------------------------------------------
------ 上传成功 ------
地址:************************************************.zip
----------------------------------------------------------