如何在Azure CI/CD管道中配置React项目的.env环境变量?
React Azure部署中.env变量读取失败的解决方法
1. 修正环境变量命名与代码引用
React框架对环境变量有强制命名规则:必须以REACT_APP_开头,否则打包时不会将变量注入到静态文件中。
- 将
.env文件中的变量名改为REACT_APP_API_URL(示例:REACT_APP_API_URL=https://your-api-endpoint) - 代码中直接通过
process.env读取,替换原有的this.REACT_URL,同时修正axios调用的两个错误:
注:原代码遗漏async GetMyEmployeeList(): Promise<IEmployee[]> { const url = `${process.env.REACT_APP_API_URL}/api/Employee`; const headers = this.getHeader(); // axios.get的第二个参数是配置对象,headers需嵌套其中 const result: AxiosResponse = await axios.get(url, { headers }); return result.data.value as IEmployee[]; }await会导致直接返回Promise而非响应数据,必须补上。
2. 本地验证打包结果
运行npm run build生成生产包后,检查build目录下的静态JS文件(如main.*.js),搜索你的API地址。如果未找到,说明:
.env文件未放在项目根目录(需与package.json同级)- 变量名未遵循
REACT_APP_前缀规则 .env文件被.gitignore忽略(正常情况不应提交到Git,后续需通过CI/CD或Azure配置传递)
3. Azure App Service环境变量配置
若本地打包正常但部署后失效,大概率是.env未被包含在部署包中(因为通常会被Git忽略),此时直接在Azure后台配置:
- 登录Azure门户,进入你的App Service → 「配置」→「应用程序设置」
- 添加新设置:键为
REACT_APP_API_URL,值为你的API地址 - 保存后App Service会自动重启,打包后的React代码会读取该变量(仅适用于支持运行时注入的部署方式,若用CI/CD打包需看下一步)
4. CI/CD管道中的变量传递
如果用Azure DevOps或GitHub Actions自动部署,需在管道中注入环境变量,确保打包时能读取到:
Azure DevOps示例(yaml)
steps: - script: npm install displayName: 'Install dependencies' - script: npm run build displayName: 'Build app' env: REACT_APP_API_URL: $(REACT_APP_API_URL) # 变量需在管道「变量」中预先配置 - task: AzureWebApp@1 displayName: 'Deploy to Azure Web App' inputs: azureSubscription: 'your-subscription' appName: 'your-app-name' package: '$(System.DefaultWorkingDirectory)/build'
GitHub Actions示例
jobs: build-and-deploy: runs-on: ubuntu-latest env: REACT_APP_API_URL: ${{ secrets.REACT_APP_API_URL }} # 变量存放在仓库Secrets中 steps: - uses: actions/checkout@v4 - name: Install dependencies run: npm install - name: Build app run: npm run build - name: Deploy to Azure uses: azure/webapps-deploy@v2 with: app-name: 'your-app-name' publish-profile: ${{ secrets.AZURE_WEBAPP_PUBLISH_PROFILE }} package: ./build
内容的提问来源于stack exchange,提问作者zaniolo10
相关产品推荐
相关产品推荐

