Skip to content

Instantly share code, notes, and snippets.

@bilelz
Last active November 10, 2022 09:47
Show Gist options
  • Save bilelz/04707e300811d2b7fe3815ede073422c to your computer and use it in GitHub Desktop.
Save bilelz/04707e300811d2b7fe3815ede073422c to your computer and use it in GitHub Desktop.
Generate app version file from package.json and git | for angular or other frameworks
/*
From https://gist.github.com/bilelz/04707e300811d2b7fe3815ede073422c
inspired by https://medium.com/@amcdnl/version-stamping-your-app-with-the-angular-cli-d563284bb94d
*/
const fs = require('fs');
const exec = require('child_process').execSync;
/* Get package.json version. */
const packageVersion = JSON.parse(
fs.readFileSync('package.json', 'UTF-8')
).version.toString();
/* Get git full revision. */
const commitSha = exec('git rev-parse HEAD').toString().trim();
/* Get git short revision. */
const commitShortSha = exec('git rev-parse --short HEAD').toString().trim(); // --short=8 if you want to be like gitlab
/* Get git branch. */
const branch = exec('git rev-parse --abbrev-ref HEAD').toString().trim();
/* Get build date. */
const buildDateUTC = new Date().toUTCString();
const appInfo = {
buildDateUTC,
packageVersion,
commitSha,
commitShortSha
branch,
};
console.log('App Informations', appInfo);
const exportedInfos = `// IMPORTANT: THIS FILE IS AUTO GENERATED! DO NOT MANUALLY EDIT OR CHECKIN!
/* tslint:disable */
export const APP_VERSION = ${JSON.stringify(appInfo, null, 2)};
/* tslint:enable */`;
fs.writeFileSync('src/environments/app.version.ts', exportedInfos, {
encoding: 'utf8',
});
@bilelz
Copy link
Author

bilelz commented Apr 6, 2021

To execute it, add a postinstall script to your package.json:

postinstall is automatically executed after each npm install

{
  "name": "My app",
  "version": "1.0.0",
  "scripts": {
    "postinstall": "node version.ts",
      [...]
  }
},

Example of a generated app.version.ts file :

// IMPORTANT: THIS FILE IS AUTO GENERATED! DO NOT MANUALLY EDIT OR CHECKIN!
/* tslint:disable */
export const APP_VERSION = {
  "buildDateUTC": "Tue, 06 Apr 2021 12:08:19 GMT",
  "packageVersion": "1.0.0-SNAPSHOT",
  "commitSha": "azerty52e4b0b4bdf1ad0faf9732891ef91042c0",
  "commitShortSha": "azerty5",
  "branch": "feature/blabla-JIRA-1234_todo-list-page"
};
/* tslint:enable */

To display/use it :

import { APP_VERSION } from 'src/environments/app.version';
// [...]
export class AppComponent implements OnInit{
  public appVersion = APP_VERSION;

  ngOnInit(): void {
    (window as any).appVersion = APP_VERSION;
  }
}

Add it to .gitignore

src/environments/app.version.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment