Add git information to create-react-app

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


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>