3

编写自动化脚本,打包前端项目用来优化 git 容量问题

 1 year ago
source link: http://surest.cn/archives/234/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

编写自动化脚本,打包前端项目用来优化 git 容量问题

Published on Mar 28, 2023 in Linux前端 with 0 comment
前期提要

主要是前端更新迭代速度超快,可能有时候一天累积打包了 10 个包,每个包平均在 3mb左右,长时间下来,就非常大了

我们使用 coding 的使用条件 容量只有 1G,导致过了一段时间就要单独处理这个事情,太麻烦了

首先我们的自动化打包流程主要是基于 coding 的持续部署

之前的打包逻辑如下:

coding -> 登录跳板机 > 跳板机执行 shell 脚本打包 > 跳板机推送 dist 文件夹 至 git 目录 -> 登录线上环境 > 拉取代码

以上的问题按正常走时没有问题的,但是我们需要进行容量处理的话,就需要 将 dist 移除,不要放置在 git 中,否则 git 文件将无限递增

由此改进后

coding -> 登录跳板机 > 跳板机执行 shell 脚本打包 > shell 脚本将 dist 压缩 build.tar.gz -> 将压缩包上传至 oss, 将远程文件名称写入 build.txt -> 推送代码 -> 登录线上环境 > 执行 shell 脚本,下载远程文件,解压安装
图片描述...

publish.sh

#!/bin/sh

# 接受多个参数,并判断参数是否为空,空的情况下退出,并抛出错误提示
if [ $# -eq 0 ]; then
    echo "sh publish.sh build master 或者 sh publish.sh build development"
    exit 1
fi


# 定义输入参数作为变量
command=$1
env=$2

# 如果第三个参数有的时候就用参数,没有的时候就自定义
if [ -z "$3" ]; then
    commit="build"
else
    commit=$3
fi


# 根据输入command 执行不同的命令
if [ "$command" = "build" ]; then
    if [ "$env" = "master" ]; then
        npm run build:master
    elif [ "$env" = "development" ]; then
        npm run build:development
    else
        echo "sh publish.sh build master 或者 sh publish.sh build development"
        exit 1
    fi
fi

# command = build 执行完毕后,执行git命令
if [ "$command" = "build" ]; then
    # 以 build 为前缀创建一个根据时间戳生成的文件名:build-202303285115.tar.xz
    prefix="build"
    timestamp=$(date +"%Y%m%d%H%M%S")
    filename="$prefix-$timestamp.tar.xz"

    # 删除当前目录下 build 为前缀的文件名
    rm -rf $prefix-*.tar.xz

    # 打包 dist 文件夹
    tar -cJvf $filename dist

    # 获取执行 node upload.js 的返回值
    url=$(node upload.js $filename)

    # 判断是否为一个 url,失败的情况下退出,并抛出错误提示
    if [[ $url != http* ]]; then
        echo "上传失败"
        exit 1
    fi
    
    git add -A
    git commit -m "$commit"
    git push origin $env

    # 将文件名输出到 build.txt 文件中
    echo $url > build.txt
fi

# command = install 执行完毕后,执行解压并删除 以build为前缀的文件
if [ "$command" = "install" ]; then
    git reset --hard origin $env

    # 读取 build.txt 文件中的文件名
    filename=$(cat build.txt)

    # 下载 filename 到本地,并且命名为 build.tar.xz
    wget $filename -O build.tar.xz

    # 解压文件
    tar -xJvf build.tar.xz

    # 删除文件
    rm -rf  build.tar.xz
fi

以上则是根据不同环境,将文件进行打包压缩并且上传

upload.js

// 使用NODE JS 将本地压缩包上传至 七牛云 cdn

const qiniu = require('qiniu');
const fs = require('fs');

// 配置七牛云账号信息
const accessKey = '*-*****';
const secretKey = '****';
const bucketName = '***';

// 接受一个参数, 如 upload.js filename
const fileName = process.argv[2];

// 如果参数不存在,则退出
if (!fileName) {
    console.log('请传入文件名');
    process.exit(1);
}

// 初始化配置
const config = new qiniu.conf.Config();
// 使用华南机房
config.zone = qiniu.zone.Zone_z2; // 选择华南地区作为上传域名
const formUploader = new qiniu.form_up.FormUploader(config);
const putExtra = new qiniu.form_up.PutExtra();

// 读取 build.txt 获取待上传的文件名称, 去除换行符
// const buildTxt = fs.readFileSync('build.txt', 'utf-8').replace(/[\n]/g, '');

// 读取本地文件
// 使用PWD
const filePath = `${process.env.PWD}/${fileName}`;
const readStream = fs.createReadStream(filePath);

// 生成上传token
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const options = {
    scope: bucketName,
};
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);

// 上传文件到七牛云
const key = `static/build/${fileName}`; // 远程文件名,不含前缀,七牛云会自动生成前缀
formUploader.putStream(uploadToken, key, readStream, putExtra, function (respErr, respBody, respInfo) {
    if (respErr) {
        throw respErr;
    }
    if (respInfo.statusCode === 200) {
        console.log(`自定义域名/${key}`);
    } else {
        console.log(`上传失败:${respBody.error}`);
    }
});

由此,自动化打包流程,就解决了我们的容量问题,存储代码是耗费不了多大空间的

我所以我们需要的是将 dist 目录、build-*.tar.xz 都从 git 中移除

所以我们需要在 .gitignore 中新增: build-*.tar.xzdist

移除 dist

由于我们历史文件 dist 已纳入到 git 中,我们不需要针对这个 dist 文件进行历史跟踪,我们将其 从 git 历史中进行删除

要将 dist 目录从 Git 的历史记录中完全移除,您需要使用 Git 中的 filter-branch 命令。具体步骤如下:


首先,确保您在执行这些操作之前备份了您的代码库。

运行以下命令来确保在 Git 中正确地忽略 dist 目录:

git rm -r --cached dist
echo "dist" >> .gitignore
git add .gitignore
git commit -m "Remove dist from git history"

这将从您的 Git 存储库中删除 dist 目录,并将其添加到 .gitignore 文件中。

接下来,使用 filter-branch 命令将 dist 目录从 Git 历史记录中彻底删除:

git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch dist -r' --prune-empty --tag-name-filter cat -- --all

这个命令会重写 Git 历史记录并删除所有与 dist 相关的内容。

最后,运行以下命令以强制推送新的 Git 历史记录:

git push origin --force --all
git push origin --force --tags

这将覆盖远程存储库中的历史记录,确保 dist 目录已被完全删除。请注意,此操作可能会影响与您共享代码库的其他开发人员,因此请确保在执行此操作之前与他们进行沟通。

本文由 邓尘锋 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为: Mar 28, 2023 at 11:36 am


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK