Wednesday, July 13, 2022

React Version Stamping Recipe

Core Java, Oracle Java, Java Tutorial and Materials, Oracle Java Career, Java Skills, Java Jobs

My view on version numbering is that we should take the build time and git SHA of our code and pass it through to the build as a version identifier. Then we can easily look at any stamped version of our application and find where it came from. To me, this is more powerful than stamping an arbitrary release number somewhere, even as a tag in the source control system.

Let’s say we’ve created this version stamp and we want to see it in a ReactJS app. Perhaps we want to write it subtly into the DOM somewhere so it’s there if we need to check which version is loaded.

Firstly, we need to push it into the build process.

We need something like this in the package.json:

"description": "BUILD_VERSION",

And then we can run a command just before executing the build on our CI server to pass in the actual build version stamp. Let’s assume it’s in an environment variable called BUILD_VERSION:

# replace the placeholder with the actual version

sed -i "s/BUILD_VERSION/${BUILD_VERSION}/g" package.json

# then build

npm run build

Then we want to make the description of the package visible to React itself. This is achieved by adding a .env file:

REACT_APP_VERSION=$npm_package_description

Which means we can then use process.env.REACT_APP_VERSION within our browser code to pick up the value that’s entered our package through the build process:<

<span className=”build-version” data-testid=”build-version-test”>

  {process.env.REACT_APP_VERSION}

</span>

As you can see here, we’ve even tagged this element with an identifier so that it’s possible for a test to output the version identifier of the app it is testing.

None of this is hard. Knowing how to put it together took a bit of time. I hope it’s useful.

Source: javacodegeeks.com

Related Posts

0 comments:

Post a Comment