在项目部署中经常需要将打包的dist按一定的名称压缩成压缩包,今天记录一下打包时生成压缩包的过程。其中有用到的npm包需要自己安装一下。
js文件放置的目录如下
compress.js内容如下:
// compress.jsimport fs from "fs";
import shell from "shelljs"
import minimist from "minimist"
import archiver from "archiver"
import {useNow, useDateFormat} from '@vueuse/core'/*** 压缩文件夹* @param sourceFolder 待压缩文件夹* @param destZip 压缩后zip文件路径 文件名* @param cb 回调函数* @param subDir 是否包一层原文件名*/
function zipFolder(sourceFolder, destZip, cb, subDir) {let output = fs.createWriteStream(destZip),archive = archiver('zip', {zlib: {level: 9}});output.on('close', () => {cb(destZip, '文件压缩成功');})output.on('error', (err) => {cb(err)})archive.pipe(output);archive.directory(sourceFolder, subDir ? sourceFolder : false);archive.finalize();
}/*** git log* @returns {Promise<unknown>}*/
function getLog() {let _cmd = `git show -s --format=%H`;return new Promise((resolve, reject) => {shell.exec(_cmd, (code, stdout, stderr) => {if (code) {reject(stderr)} else {resolve(stdout)}})})
}async function toZip() {// eslint-disable-next-line no-undefconst args = minimist(process.argv.slice(2));let _gitLog = await getLog();let date = useDateFormat(useNow(), 'YYMMDD'),commit = _gitLog.substring(0, 8),pre = args.pre || '', //项目前缀version = args.version || '',//版本号beta = args.beta || '',//测试版subDir = args.subDir,//压缩是否套一层输出的文件夹 不是设置这个参数即不包一层原文件夹sourceFolder = args.output || 'dist',//打包输出的文件夹destZip = `${pre}-WEB-${version}-${commit}${beta && `-${beta}`}-${date.value}.zip`;zipFolder(sourceFolder, destZip, (err, msg) => {console.log(err, msg)}, subDir);
}toZip();
最后还需要配置一下package.json, 如下: