For a small React application using NPM I needed to automatically increment a build number on every production build without having to remember to do it, and then I needed to refer to that version number within the application in order to display in on the site’s footer.
The solution is to essentially call a NodeJs script from npm build script definition whcih updates a metadata JSON file within the prpoject to increment the build version number by 1. This file can then be read within the React code as required to display the currnt vuild verson.
First we need to store the build version numbers in a JSON file:
Only the buildRevision will be updated automatically as we will want manual control over the major/minor numbers as we implement semantic versioning.
The NodeJS Script (generate-buildno.js) is below. This opens the metadata.json file, reads the buildRevision value and then updates it by 1 before saving the file:
To call this script at build time we update the package.json file and change the build command to call our script first, before the normal build command:
Now when we call npm run build the JSON file we be updated and the build revision number incremented. The React code that needs to display the app version number just has to read the metadata.json file like the example React Components below:
Remember after building the application to commit your changed metadata.json file into source control!