Home > Software design >  Change environment variable value of react app using azure devops - Deployment on aws (s3)
Change environment variable value of react app using azure devops - Deployment on aws (s3)

Time:06-24

I have a react application in which they are getting backend api address by using Environment variable. Below in the example:

this._baseUrl = process.env.API_GATEWAY;

In local development environment, development team create .env. file and set environment variable value in that file, to call backend api and every things work fine, like below.

API_GATEWAY=http://localhost:3000

When i create CI/CD pipeline for same project then every things works fine and application is also successfully deployed on AWS (s3 bucket) but i am not able to change the value of environment variable while building the project using npm, like below:

    - script: |
        npm run build
     displayName: 'npm build'
     env:
       API_GATEWAY: $(envAppApi)

API_GATEWAY used above is the name of environment variable used in code and $(envAppApi) is variable defined in variable group.

But when application is deployed on AWS then environment variable value not changed and it shows below error.

mutation.js:106 ReferenceError: process is not defined
    at new e (http-api.ts:17:42)
    at Function.value (http-api.ts:24:12)
    at Object.mutationFn (Auth.ts:13:26)
    at Object.fn (mutation.js:132:31)
    at c (retryer.js:95:31)
    at new u (retryer.js:156:3)
    at t.executeMutation (mutation.js:126:20)
    at mutation.js:86:20

(http-api.ts:17:42) => This is the same line where API_GATEWAY environment variable is set and already showed above.

Problem statement: Is there is any way that we can update the value of environment variable while creating CI/CD pipeline? so the application run successfully. Thanks.

Note: I don't want to use .env. file in my pipeline for updating environment values in react application.

CodePudding user response:

Is there is any way that we can update the value of environment variable while creating CI/CD pipeline?

Yes. I suggest that you can use RegEx Match & Replace task from RegEx Match & Replace.

This task will use regular expressions to match fields in the file.

Here is an example:

steps:
- task: RegExMatchReplace@2
  displayName: 'RegEx Match & Replace'
  inputs:
    PathToFile: test.js
    RegEx: 'this._baseUrl = ([a-zA-Z] (\.[a-zA-Z] ) )_[a-zA-Z] ;'
    ValueToReplace: ' this._baseUrl = $(envAppApi)'

Then the value will update.

You can use this site to convert the regular expressions : Regex Generator

  • Related