Core Java

React Version Stamping Recipe

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.

Published on Java Code Geeks with permission by Ashley Frieze, partner at our JCG program. See the original article here: React Version Stamping Recipe

Opinions expressed by Java Code Geeks contributors are their own.

Ashley Frieze

Software developer, stand-up comedian, musician, writer, jolly big cheer-monkey, skeptical thinker, Doctor Who fan, lover of fine sounds
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button