video-flow-b/compile_prod.sh
2025-09-29 15:26:22 +08:00

106 lines
3.0 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
BRANCH_NAME="prod"
# 修改项目名称
PROJECT_NAME="video-flow-$BRANCH_NAME-frontend"
# 设置日志文件路径
LOGFILE="build_and_copy.log"
# 记录开始时间
echo "Build process started at $(date)" | tee $LOGFILE
# 获取当前分支名
current_branch=$(git rev-parse --abbrev-ref HEAD)
# 指定并加载环境变量文件prod 使用 .env.production
ENV_FILE=".env.production"
# 兼容 KEY=VALUE 与 KEY: VALUE 的 .env 行为,忽略注释与空行
load_env_file() {
local file="$1"
if [ -f "$file" ]; then
echo "Loading environment from $file" | tee -a $LOGFILE
while IFS= read -r raw || [ -n "$raw" ]; do
# 去除注释与首尾空白
local line="${raw%%#*}"
line="$(echo "$line" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
[ -z "$line" ] && continue
# 将 KEY: VALUE 转换为 KEY=VALUE
if echo "$line" | grep -q '^[A-Za-z_][A-Za-z0-9_]*[[:space:]]*:'; then
line="$(echo "$line" | sed -E 's/^([A-Za-z_][A-Za-z0-9_]*)[[:space:]]*:[[:space:]]*/\1=/')"
fi
# 仅处理合法的 KEY=VALUE 形式
if echo "$line" | grep -q '^[A-Za-z_][A-Za-z0-9_]*='; then
# 去除等号两侧空白
line="$(echo "$line" | sed -E 's/^[[:space:]]*//; s/[[:space:]]*$//; s/[[:space:]]*=[[:space:]]*/=/')"
export $line
fi
done < "$file"
else
echo "未找到 $file,继续使用当前环境变量" | tee -a $LOGFILE
fi
}
load_env_file "$ENV_FILE"
# 设置 NODE_ENV 为 production
export NODE_ENV="production"
# 打包之前,需要检查是否在 prod 分支,工作区是否干净,是否和远程分支一致
if [ "$(git branch --show-current)" != "$BRANCH_NAME" ]; then
echo "当前分支不是 prod 分支"
exit 1
fi
# 检查工作区是否干净
if [ -n "$(git status --porcelain)" ]; then
echo "工作区不干净"
exit 1
fi
# 检查远程分支是否和本地分支一致
if [ "$(git rev-parse HEAD)" != "$(git rev-parse origin/$BRANCH_NAME)" ]; then
echo "本地分支和远程分支不一致"
exit 1
fi
# 检查当前分支并运行相应的 npm 命令
if [ "$current_branch" = "$BRANCH_NAME" ]; then
echo "On prod branch, building project..." | tee -a $LOGFILE
PROFILE_ENV=$BRANCH_NAME
# 安装依赖并构建
yarn install
yarn build
# 准备dist目录
mkdir -p dist
cp -r .next dist/
cp -r public dist/
cp package.json dist/
cp package-lock.json dist/
else
echo "On non-prod branch ($current_branch), exiting"
exit 1
fi
# 创建tar包
tar -czvf $PROJECT_NAME-$PROFILE_ENV.tar.gz dist
# 记录结束时间
echo "Build process completed at $(date)" | tee -a $LOGFILE
# 上传到 nexus
echo "upload to nexus at $(date)" | tee -a $LOGFILE
curl -u 'admin':'YZ9Gq6=8\*G|?:,' --upload-file $PROJECT_NAME-$PROFILE_ENV.tar.gz https://repo.qikongjian.com/repository/frontend-tar-files/
# 清理构建文件
rm -rf dist
rm $PROJECT_NAME-$PROFILE_ENV.tar.gz