Search code examples
angulartypescriptangular-cliangular-cli-v6

Angular CLI to modify a TS file before building?


I am using Angular 6 and Angular CLI to build with AOT. The SPA has an About dialog to tell current frontend version which is basically YYMMDD:mm. I stored the version in environments/environment.ts:

export const AppConfigConstants: AppConfigConstantsType = {

    version: '180709.13',

};

Currently before running

ng build --configuration=production

I have to modify the version manually. It will be better if the update of the version number could be automated.

Is there a good function in Angular CLI to modify the TS file? or you have some other solution?


Solution

  • I a batch files to call ng build generally.

    The batch file is like this:

    cd %~dp0NGSource
    
    for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x
    
    set today=%MyDate:~0,4%%MyDate:~4,2%%MyDate:~6,2%%time:~0,2%%time:~3,2%
    
    @echo const BUILD_TIME={buildTime: %today%} > src\conf\buildTime.js
    
    ng build --configuration=production
    

    And buildTime.js is included in the scripts node of angular.json, so it is bundled in scripts.xxxxx.js. MY TS code access this file through such declaration:

    declare const BUILD_TIME: {
        buildTime?: string;
    }
    
    interface AppConfigConstantsType {
        version: string;
        buildTime?: string;
    }
    
    export const AppConfigConstants: AppConfigConstantsType = {
        version: '2.3',
        ...(typeof BUILD_TIME === 'undefined' ? { buildTime: 'Unknown' } : BUILD_TIME),
    };
    

    At the end, I had decided to separate the version number and the build number. If you want to combine them into one string, it shouldn't be hard for you to adjust the codes above.