更新 编译时环境变量控制

This commit is contained in:
moux1024 2025-09-29 15:26:22 +08:00
parent 86582bfe7d
commit 84265e683b
2 changed files with 60 additions and 18 deletions

View File

@ -16,15 +16,36 @@ current_branch=$(git rev-parse --abbrev-ref HEAD)
# 指定并加载环境变量文件dev 使用 .env.development
ENV_FILE=".env.development"
if [ -f "$ENV_FILE" ]; then
echo "Loading environment from $ENV_FILE" | tee -a $LOGFILE
set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a
else
echo "未找到 $ENV_FILE,继续使用当前环境变量" | tee -a $LOGFILE
fi
# 兼容 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 为 development避免默认使用 production
export NODE_ENV="development"

View File

@ -16,15 +16,36 @@ current_branch=$(git rev-parse --abbrev-ref HEAD)
# 指定并加载环境变量文件prod 使用 .env.production
ENV_FILE=".env.production"
if [ -f "$ENV_FILE" ]; then
echo "Loading environment from $ENV_FILE" | tee -a $LOGFILE
set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a
else
echo "未找到 $ENV_FILE,继续使用当前环境变量" | tee -a $LOGFILE
fi
# 兼容 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"