Angular - include basic git details
Table of contents
In this article, I'll show you how to include basic GIT data in the Angular application. The data will be dumped to src/assets/version.json
file and will consist of:
short hash
long hash
branch name
commit date
Set up the app
Init the test app with default settings:
ng new app --defaults=true
Navigate to the app directory:
cd app
Install the dependencies. I'll be using the git-rev-sync
library.
npm i git-rev-sync
Implement the solution
Create a .gitignore
file the src/assets
directory and add the following content. This will prevent the file from being included in the repository.
version.json
Create the script file dump-git-info.js
in the app's main directory. The flow is quite simple:
import the libraries
read git data
write file
// dump-git-info.js
const git = require('git-rev-sync');
const { writeFileSync } = require('fs');
const version = {
short: git.short(),
long: git.long(),
branch: git.branch(),
date: git.date(),
};
writeFileSync('./src/assets/version.json', JSON.stringify(version));
You can run the script with the following command:
npm i git-rev-sync
Check the file ./src/assets/version.json
and you should see output similar to:
{"short":"386e4a5","long":"386e4a55e9e96018465754de172c351c68f7ff1f","branch":"master","date":"2023-04-15T13:45:30.000Z"}
Add the script to package.json
:
{
"scripts": {
"dump-git-info": "node dump-git-info.js",
...
Also, add prebuild
hook to run it automatically:
{
"scripts": {
"prebuild": "npm run dump-git-info",
...
From now on, whenever you run npm run build
the version.json
will be also created and accessible through /assets/version.json
url in the browser.
$ npm run build
> app@0.0.0 prebuild
> npm run dump-git-info
> app@0.0.0 dump-git-info
> node dump-git-info.js
> app@0.0.0 build
> ng build
> Generating browser application bundles (phase: setup)...