问题
We have a create-react-app project that gets some build parameters from the environment (e.g. Auth0 config), meaning that these environment variables affect the react build.
We're working on an Azure DevOps build pipeline for this project, and while it's straighforward to define the variables on the pipeline's variables page, it's not obvious how to set them differently depending on which branch is being built.
For example, we'd like the dev
branch to build using or development tenant in Auth0, while release and master branches should build using or production tenant in Auth0 (same variable, two different values).
Is there a documented/supported approach to this? Or some "best practice"?
I've read that you can modify variables from PowerShell scripts, e.g. like in this post. Is that the best way to do it? How can the script inspect which branch is being built, to choose the right set of values?
I also found that DevOps has a concept of variable groups. I haven't read up on it yet, but would it be a good approach to define a variable group per branch (or branch pattern) and have the script select which group to apply? How?
回答1:
How to setup DevOps build for creat-react-app project with different environment vars depending on built branch?
At this moment, I am afraid using Power-Shell script task in your build definition to get the source branch name and then set environment variables based on the branch name is a good choose. Because nested variables are not yet supported in the build pipelines.
The PowerShell script like:
$branch = $Env:Build_SourceBranchName
Write-Host "Current branch is $branch"
if ($branch -eq "Dev")
{
Write-Host ("##vso[task.setvariable variable=testvar]testvalue")
}
else (($branch -eq "master") -or (($branch -eq "release")))
{
Write-Host ("##vso[task.setvariable variable=testvar2]testvalue2")
}
Check the Logging Command during the build for some more details.
Besides, for the variable groups, we could use VSTS Variable Groups per environment for release definition, but it not work for build definition. Check this thread for some details.
Hope this helps.
来源:https://stackoverflow.com/questions/54177906/how-to-setup-devops-build-for-creat-react-app-project-with-different-environment