How can i change my React .env values during a pipeline run in Azure Devops

Viewed 2434

I have created a react app with create-react-app. I'm now in a phase where i want to deploy to different environments.

I am using a .env and .env.local file for storing information my app needs to run properly.

The env.local is for my local development. I would like to make the .env file variable so that i can change the values during my build or release phase. When i use npm run build, i want to make build for a specific environemnt using specific environment values.

I am using a YAML file(Azure Devops) for setting up my build and release process.

So how can i make the values in my .env file variable so that i can set my react variable based on the environment i am deploying to?

1 Answers

a.Install the extension Replace Tokens.

b.Add variable test = test002

c.Target file: Test.env content: #{test}#

d.Check the sample YAML sample:

pool:
  vmImage: 'windows-latest'
  
steps:
- powershell: |
   $ourfilesdata = Get-Content "test.env"
   Write-Output $ourfilesdata 
  displayName: 'PowerShell Script'

- task: qetza.replacetokens.replacetokens-task.replacetokens@3
  displayName: 'Replace tokens in **/*.env'
  inputs:
    targetFiles: '**/*.env'
    encoding: 'auto'
    writeBOM: true
    actionOnMissing: 'warn'
    keepToken: false
    tokenPrefix: '#{'
    tokenSuffix: '}#'
    useLegacyPattern: false
    enableTelemetry: true

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $ourfilesdata = Get-Content "test.env"
      Write-Output $ourfilesdata
Related