How to include git revision into angular-cli application?

前端 未结 9 2180
甜味超标
甜味超标 2021-01-31 16:40

I need to display git revision on my angular2 application\'s about page. The project is based on angular-cli.

How can build be extended so git revision is put for exampl

9条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 16:52

    Display branch name and commit hash

    I have a little different approach, inspired by answers repo Seba Arce and Jeroen , in main project directory:

    • execute: npm install git-rev-sync --save (this lib give acces to hash and branch name)
    • add file git-version-gen.js with following body

    const git  = require('git-rev-sync');
    const { writeFileSync } = require('fs');
    
    const gitInfo = { commit: git.short(), commitLong: git.long(), branch: git.branch() };
    const ts = 'export const gitVersion = ' + JSON.stringify(gitInfo, null, 2);
    
    writeFileSync('src/environments/git-version.ts', ts);

    • in package.json in scripts add "build": "node git-version-gen.js && ng build ..."
    • in your main app file e.g. app.component.ts use it as follows

    import { gitVersion } from '../../../environments/git-version';
    
    // ...
    
      constructor() {
        console.log(`GIT branch:`,gitVersion.branch);
        console.log(`GIT commit:`,gitVersion.commit);
      }

    What are advantages of use this?

    • we create here src/environments/git-version.ts file so this is TypeScript, not .json - similar like you environments files - this will turn on support from your code editor (e.g VSCode)

    • you have acces to commit hash nad branch name (lib git-describe not gives acces to branch name)

    • if you commit generated git-version.ts file instead put it to .gitignore then project will run without build (e.g. by ng serve ...) and fresh developers will not be confused that there is missing some 'mystic' file... - however choice is up to you.

    • cross platform - tested on Azure (windows), MacOs (~linux-like)

提交回复
热议问题