When creating a react app using create-react-app, we may sometimes want to inject some environment variables at build time.
For instance, our team wanted to console.log the build time, app version and some git information when the app starts.
This is the solution we came up with.
The Build script
We added a node script to scripts/build.js. The script uses shelljs to append information to the environment and run react-scripts and simple-git to execute git commands.
const path = require('path');
const shell = require('shelljs');
const simpleGit = require('simple-git');
const { version } = require('../package.json');
const args = process.argv.slice(2);
const isDev = args.includes('--dev');
if (!shell.which('git')) {
shell.echo('Cannot build without git');
shell.exit(1);
}
if (!shell.which('yarn')) {
shell.echo('Cannot build without yarn');
shell.exit(1);
}
const workingDir = path.resolve(__dirname, '../');
const git = simpleGit(workingDir);
function getCurrentBranch() {
return new Promise((fulfill, reject) => {
git.status((err, status) => {
if (err) {
reject(err);
return;
}
fulfill(status.current);
});
});
}
function getCurrentCommit() {
return new Promise((fulfill, reject) => {
git.revparse(['HEAD'], (err, hash = '') => {
if (err) {
reject(err);
return;
}
fulfill(hash.slice(0, 7));
});
});
}
(async () => {
try {
const branch = await getCurrentBranch();
const commit = await getCurrentCommit();
const buildTime =