How to include git revision into angular-cli application?

前端 未结 9 2295
甜味超标
甜味超标 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 17:08

    The other answers were helpful, but I preferred a more simple, direct approach. Here's mine.

    Run npm install git-describe --save-dev. Then add git-version.js to the root:

    // This script runs operations *synchronously* which is normally not the best
    // approach, but it keeps things simple, readable, and for now is good enough.
    
    const { gitDescribeSync } = require('git-describe');
    const { writeFileSync } = require('fs');
    
    const gitInfo = gitDescribeSync();
    const versionInfoJson = JSON.stringify(gitInfo, null, 2);
    
    writeFileSync('git-version.json', versionInfoJson);
    

    Optionally you can add /git-version.json to your .gitignore file.

    Update your package.json to do something like this:

    "scripts": {
      "build": "node git-version.js && ng build"
    }
    

    Then add version-info.ts to the root of your project:

    export const versionInfo = (() => {
      try {
        // tslint:disable-next-line:no-var-requires
        return require('../../git-version.json');
      } catch {
        // In dev the file might not exist:
        return { tag: 'v0.0.0', hash: 'dev' };
      }
    })();
    

    And import the versionInfo in your app.component.ts or anywhere else you'd want to use it.

提交回复
热议问题