Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
July 7, 2020 03:30 pm GMT

Add commit hash version to your Reactapp

Problem

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).

Solution (Step-by-step)

  • 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 webpack.config.js
const commitHash = require('child_process').execSync('git rev-parse --short HEAD')
Calculated commit hash should be wrapped with DefinePlugin function in plugins array.

new webpack.DefinePlugin({
'COMMIT_HASH': JSON.stringify(commitHash),
})

That's all. Now your hash is available in the React app code process.env.REACT_APP_VERSION

Note: the environment variables are embedded during the build time. Since Create React App produces a static HTML/CSS/JS bundle, it cant 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

That's it.

Happy Codding !


Original Link: https://dev.to/nastassiadanilova/add-commit-hash-version-to-your-react-app-n3n

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To