npm run build 以非常具体的方式获取环境变量:仅使用 .env 文件,如此处所述。
使用
npm run build
和 npx serve -s build
在本地构建时,它可以工作并且变量会传递到应用程序构建。
我现在想要配置在 github 上构建操作。我在那里设置了环境变量,但
npm
不知道它们。如何让他们进入构建?
这是我的构建步骤,但这并不重要
- name: Build
shell: bash
env:
REACT_APP_API_URL: ${{ env.REACT_APP_API_URL }}
run: |
npm install env-cmd or npm install -g env-cmd
cd frontend
mkdir -p build_logs
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
export REACT_APP_BUILD_TIME=$(TZ=America/Argentina/Buenos_Aires date +"%Y-%m-%d %H:%M:%S")
echo -e "\e[32mBuilding with environment variables:\e[0m"
env
echo -e "\e[32m$(pwd)\e[0m"
npm run build || (echo -e "\e[31mBuild step failed.\e[0m" && exit 1)
我最终在构建之前生成了 .env 文件,这给出了
npm build
它想要的东西。
- name: Build
shell: bash
env:
REACT_APP_API_URL: ${{ env.REACT_APP_API_URL }}
run: |
npm install env-cmd or npm install -g env-cmd
cd frontend
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
export REACT_APP_BUILD_TIME=$(TZ=America/Argentina/Buenos_Aires date +"%Y-%m-%d %H:%M:%S")
echo -e "\e[32mBuilding with environment variables:\e[0m"
env
echo -e "\e[32m$(pwd)\e[0m"
# Create .env file with environment variables for the build
echo "TIMESTAMP=${TIMESTAMP}" > .env
echo "REACT_APP_API_URL=${REACT_APP_API_URL}" >> .env
echo -e "\e[32mCreated .env file with TIMESTAMP and REACT_APP_API_URL.\e[0m"
npm run build || (echo -e "\e[31mBuild step failed.\e[0m" && exit 1)
rm -f .env
echo -e "\e[32mDeleted .env file after build.\e[0m"