3

How do I use variable defined for the pipeline in React Project?

Currently, I have build variable defined in the .yml file like that

variables:
  src: "virtual-furnace-app"
  dest: "$(src)/build"
  REACT_APP_VERSION: $(Build.BuildNumber)

and in the front end code, I have tried to accessing it like that but it is undefined

export const REACT_APP_VERSION = process.env.NODE_ENV === "development" ? `v${pjson.version} (Development build)` : `v${pjson.version} (${process.env.REACT_APP_VERSION})` ;
riQQ
  • 9,878
  • 7
  • 49
  • 66
Ondřej Ševčík
  • 1,049
  • 3
  • 15
  • 31
  • these are never accessible in the front end. unless you send it specifially – Sujit.Warrier Sep 25 '20 at 06:44
  • Ok, is there any other way how to get build number in the Azure build displayed in frontend? – Ondřej Ševčík Sep 25 '20 at 06:50
  • I assume you are serverside rendering. why dont you send the version number along with the HTML – Sujit.Warrier Sep 25 '20 at 07:02
  • You can consider setting a variable (e.g. APP_VERSION) in a .env file from your build pipeline. Then in app code load that using `dotenv` package. https://www.twilio.com/blog/working-with-environment-variables-in-node-js-html – krishg Sep 25 '20 at 09:31

2 Answers2

2

After while I found solution myself.

So in the code, I check if we are on localhost NODE_ENV === development and if not I will read variable injected to React script process.env.REACT_APP_VERSION

import pjson from "../../package.json"
export const REACT_APP_VERSION = process.env.NODE_ENV === "development" ? `v${pjson.version} (Development build)` : `v${pjson.version} (${process.env.REACT_APP_VERSION})` ;

Azure Pipeline yml code

REACT_APP_VERSION=$(BuildID) yarn build
Ondřej Ševčík
  • 1,049
  • 3
  • 15
  • 31
0

How to use Azure Pipeline variable in JavaScript (React) project?

You could try to use a .env file to store the variables, then use them in a React Native app.

You can reference this blog for details : How to gracefully use Environment Variables in a React Native app.

Also find some similar threads in SO, you can reference them can check if that helps:

Besides, you could also try to set REACT_APP_VERSION in the start of your script as well, e.g. "scripts": { "start": "cross-env REACT_APP_VERSION=$REACT_APP_VERSION react-scripts start" }

Leo Liu
  • 71,098
  • 10
  • 114
  • 135