Check the current build version to be sure that everything is up-to-date. Ideally in some unnoticeable for user place on the page (if you have any reasons not to use console in this case).
- Get the last git commit hash from the command line
git rev-parse --short HEAD
- Execute the script above with Node.js. The best option to do this is with Node.js child_process.
child_process.execSync(git rev-parse --short HEAD)
The only thing you should know here is that
execSync allows you to execute the command synchronously.
- Create an environment variable that contains a necessary hash. By default, your variable should be starting with REACT_APP_. In other cases, it would be ignored.
There are several ways to do it actually. The first one is to replace your standard start and build project commands in
package.json with this one
"start": "export REACT_APP_VERSION=$(git rev-parse HEAD) && react-scripts start",
"build": "export REACT_APP_VERSION=$(git rev-parse HEAD) && react-scripts build"
or just insert this line to your
const commitHash = require('child_process').execSync('git rev-parse --short HEAD')
Calculated commit hash should be wrapped with
DefinePlugin function in plugins array.
That's all. Now your hash is available in the React app code
Note: the environment variables are embedded during the build time. Since Create React App produces a static HTML/CSS/JS bundle, it can’t possibly read them at runtime. To read them at runtime, you would need to load HTML into memory on the server and replace placeholders in runtime, as described here. Alternatively, you can rebuild the app on the server anytime you change them. Create React App docs
- It's better to store the value of such variables in any global store like Redux or just as a global variable
window.VERSION = process.env.REACT_APP_VERSION
Happy Codding ⌨️! ❤️