Add git information to create-react-app
node.jsReactjsGitCreate React-Appnode.js Problem Overview
In development, I want to be able to see the build information (git commit hash, author, last commit message, etc) from the web. I have tried:
- use child_process to execute a git command line, and read the result (Does not work because browser environment)
- generate a buildInfo.txt file during
npm build
and read from the file (Does not work because fs is also unavailable in browser environment) - use external libraries such as "git-rev"
The only thing left to do seems to be doing npm run eject
and applying https://www.npmjs.com/package/git-revision-webpack-plugin , but I really don't want to eject out of create-react-app. Anyone got any ideas?
node.js Solutions
Solution 1 - node.js
On a slight tangent (no need to eject and works in develop), this may be of help to other folk looking to add their current git commit SHA into their index.html as a meta-tag by adding:
REACT_APP_GIT_SHA=`git rev-parse --short HEAD`
to the build script in the package.json and then adding (note it MUST start with REACT_APP... or it will be ignored):
<meta name="ui-version" content="%REACT_APP_GIT_SHA%">
into the index.html in the public folder.
Within react components, do it like this:
<Component>{process.env.REACT_APP_GIT_SHA}</Component>
Solution 2 - node.js
I created another option inspired by Yifei Xu's response that utilizes es6 modules with create-react-app. This option creates a javascript file and imports it as a constant inside of the build files. While having it as a text file makes it easy to update, this option ensures it is a js file packaged into the javascript bundle. The name of this file is _git_commit.js
package.json scripts:
"git-info": "echo export default \"{\\\"logMessage\\\": \\\"$(git log -1 --oneline)\\\"}\" > src/_git_commit.js",
"precommit": "lint-staged",
"start": "yarn git-info; react-scripts start",
"build": "yarn git-info; react-scripts build",
A sample component that consumes this commit message:
import React from 'react';
/**
* This is the commit message of the last commit before building or running this project
* @see ./package.json git-info for how to generate this commit
*/
import GitCommit from './_git_commit';
const VersionComponent = () => (
<div>
<h1>Git Log: {GitCommit.logMessage}</h1>
</div>
);
export default VersionComponent;
Note that this will automatically put your commit message in the javascript bundle, so do ensure no secure information is ever entered into the commit message. I also add the created _git_commit.js to .gitignore so it's not checked in (and creates a crazy git commit loop).
Solution 3 - node.js
It was impossible to be able to do this without eject
ing until Create React App 2.0 (Release Notes) which brought with it automatic configuration of Babel Plugin Macros which run at compile time. To make the job simpler for everyone, I wrote one of those macros and published an NPM package that you can import to get git information into your React pages: https://www.npmjs.com/package/react-git-info
With it, you can do it like this:
import GitInfo from 'react-git-info/macro';
const gitInfo = GitInfo();
...
render() {
return (
<p>{gitInfo.commit.hash}</p>
);
}
The project README has some more information. You can also see a live demo of the package working here.
Solution 4 - node.js
So, turns out there is no way to achieve this without ejecting, so the workaround I used is:
-
in package.json, define a script
"git-info": "git log -1 --oneline > src/static/gitInfo.txt"
-
add
npm run git-info
for both start and build -
In the config js file (or whenever you need the git info), i have
const data = require('static/gitInfo.txt') fetch(data).then(result => { return result.text() })
Solution 5 - node.js
My approach is slightly different from @uidevthing's answer. I don't want to pollute package.json file with environment variable settings.
You simply have to run another script that save those environment variables into .env
file at the project root. That's it.
In the example below, I'll use typescript but it should be trivial to convert to javascript anyway.
package.json
If you use javascript it's node scripts/start.js
...
"start": "ts-node scripts/start.ts && react-scripts start",
scripts/start.ts
Create a new script file scripts/start.ts
const childProcess = require("child_process");
const fs = require("fs");
function writeToEnv(key: string = "", value: string = "") {
const empty = key === "" && value === "";
if (empty) {
fs.writeFile(".env", "", () => {});
} else {
fs.appendFile(".env", `${key}='${value.trim()}'\n`, (err) => {
if (err) console.log(err);
});
}
}
// reset .env file
writeToEnv();
childProcess.exec("git rev-parse --abbrev-ref HEAD", (err, stdout) => {
writeToEnv("REACT_APP_GIT_BRANCH", stdout);
});
childProcess.exec("git rev-parse --short HEAD", (err, stdout) => {
writeToEnv("REACT_APP_GIT_SHA", stdout);
});
// trick typescript to think it's a module
// https://stackoverflow.com/a/56577324/9449426
export {};
The code above will setup environment variables and save them to .env
file at the root folder. They must start with REACT_APP_
. React script then automatically reads .env
at build time and then defines them in process.env
.
App.tsx
...
console.log('REACT_APP_GIT_BRANCH', process.env.REACT_APP_GIT_BRANCH)
console.log('REACT_APP_GIT_SHA', process.env.REACT_APP_GIT_SHA)
Result
REACT_APP_GIT_BRANCH master
REACT_APP_GIT_SHA 042bbc6
More references:
Solution 6 - node.js
If your package.json
scripts are always executed in a unix environment you can achieve the same as in @NearHuscarl answer, but with fewer lines of code by initializing your .env
dotenv file from a shell script. The generated .env
is then picked up by the react-scripts in the subsequent step.
"scripts": {
"start": "sh ./env.sh && react-scripts start"
"build": "sh ./env.sh && react-scripts build",
}
where .env.sh
is placed in your project root and contains code similar to the one below to override you .env
file content on each build or start.
{
echo BROWSER=none
echo REACT_APP_FOO=bar
echo REACT_APP_VERSION=$(git rev-parse --short HEAD)
echo REACT_APP_APP_BUILD_DATE=$(date)
# ...
} > .env
Since the .env
is overridden on each build, you may consider putting it on the .gitignore
list to avoid too much noise in your commit diffs.
Again the disclaimer: This solution only works for environments where a bourne shell interpreter or similar exists, i.e. unix.
Solution 7 - node.js
You can easily inject your git information like commit hash into your index.html using CRACO and craco-interpolate-html-plugin. Such way you won't have to use yarn eject
and it also works for development server environment along with production builds.
After installing CRACO the following config in craco.config.js
worked for me:
const interpolateHtml = require('craco-interpolate-html-plugin');
module.exports = {
plugins: [
{
plugin: interpolateHtml,
// Enter the variable to be interpolated in the html file
options: {
BUILD_VERSION: require('child_process')
.execSync('git rev-parse HEAD', { cwd: __dirname })
.toString().trim(),
},
},
],
};
and in your index.html
:
<meta name="build-version" content="%BUILD_VERSION%" />
Here are the lines of code to add in package.json
to make it all work:
"scripts": {
"start": "craco start",
"build": "craco build"
}