How to include git revision into angular-cli application?

前端 未结 9 2182
甜味超标
甜味超标 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:59

    For angular 6

    1 Install git-describe as a dev dependency

     npm i git-describe -s
    

    2 On your root project create a grab-git-info.js

       const { gitDescribeSync } = require('git-describe');
       const { writeFileSync } = require('fs');
       const path = require('path');
       const info = gitDescribeSync();
       const infoJson = JSON.stringify(info, null, 2);
       writeFileSync(path.join(__dirname, '/src/git-version.json'), infoJson);
    

    The output of the grab-git-info.js script will be the ‘git-version.json’ file under /src/ which will contain all the git info needed by our app.

    In order to be able to import the json file (or any other json file) we need to add a definition file declaring of the added module so that the Typescript compiler will recognize it.

    1. Under your /src create typings.d.ts file (read more about typings.d.ts here: https://angular.io/guide/typescript-configuration#typescript-typings)

    /src/typings.d.ts:

     declare module '*.json' {
       const value: any;
       export default value;
     }
    

    From this point on you can import any json file located under /src as a module!

    In your component you can import this json

     import * as data from '../../../git-version.json';
     ...
     public git = data;
    

    In the html

     Rev: {{git.hash}}
    

    Finally Add and most important, run the script before build

    In package.json add:

    "scripts": {
      "ng": "ng",
      "start": "ng serve",
      "build": "node grab-git-info && ng build",
    

    And run the app with

     npm run build
    

提交回复
热议问题