React项目中export命令无法按Git分支设置.env环境变量问题
问题原因
你遇到的核心问题是npm脚本中每个命令在独立子shell中执行:build.sh && react-scripts start的逻辑是先启动子shell运行build.sh,脚本里的export仅对这个子shell生效;当build.sh执行完毕,子shell关闭、变量销毁,后续启动的react-scripts进程在新子shell中,根本拿不到之前导出的变量。另外,你在.env文件中固定设置了REACT_APP_ENV=development,react-scripts会优先读取该文件配置,这也导致变量始终显示为development。
解决方案
以下是几种可行的修复方式,按推荐优先级排序:
方式一:用source执行shell脚本(最简单有效)
修改package.json的scripts,用.或source命令执行build.sh,让脚本在当前shell中运行,导出的变量能直接传递给后续的react-scripts:
"scripts": { "start": ". ./build.sh && react-scripts start", "build": ". ./build.sh && react-scripts build", "test": ". ./build.sh && react-scripts test", "eject": ". ./build.sh && react-scripts eject" }
注意:
. ./build.sh中的空格不能省略,第一个.是source命令的简写,后面的./build.sh是脚本路径。
方式二:在脚本中直接传递环境变量给命令
修改build.sh让它输出环境变量赋值语句,再在npm脚本中将输出作为前缀传给react-scripts:
- 修改
build.sh内容:
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD) if [ "$BRANCH_NAME" == "production" ] then echo "REACT_APP_ENV=production" elif [ "$BRANCH_NAME" == "staging" ] then echo "REACT_APP_ENV=staging" else echo "REACT_APP_ENV=development" fi
- 修改
package.json的scripts:
"scripts": { "start": "$(./build.sh) react-scripts start", "build": "$(./build.sh) react-scripts build", "test": "$(./build.sh) react-scripts test", "eject": "$(./build.sh) react-scripts eject" }
方式三:使用cross-env实现跨平台兼容(适合多系统开发)
如果需要在Windows等非Unix系统运行脚本,推荐用cross-env统一环境变量设置方式:
- 安装
cross-env:
npm install cross-env --save-dev
- 修改
build.sh:
#!/bin/bash BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD) if [ "$BRANCH_NAME" == "production" ] then cross-env REACT_APP_ENV=production "$@" elif [ "$BRANCH_NAME" == "staging" ] then cross-env REACT_APP_ENV=staging "$@" else cross-env REACT_APP_ENV=development "$@" fi
- 修改
package.json的scripts:
"scripts": { "start": "./build.sh react-scripts start", "build": "./build.sh react-scripts build", "test": "./build.sh react-scripts test", "eject": "./build.sh react-scripts eject" }
验证步骤
修改完成后可按以下步骤确认:
- 切换到staging分支,执行
npm run start - 在React代码中打印
process.env.REACT_APP_ENV,确认是否输出staging - 也可先手动执行
. ./build.sh,再用echo $REACT_APP_ENV验证变量是否正确设置,随后启动项目
内容的提问来源于stack exchange,提问作者Asad Zubair Bhatti
相关产品推荐
相关产品推荐

