How to insert a Build Number or Timestamp at build time in AngularCLI

There's no need to replace-in-file.

Simple Solution: Using Angular Environments

Just inside your desired environment.*.ts file (For more information about environments read angular-2-and-environment-variables) require package.json like so:

export const environment = {
    version: require('../package.json').version
};

Then inside your app import environment:

import { environment } from '../environments/environment';

And you have environment.version. If you get cannot find name 'require' error, Read this answer

More info

Note: As @VolodymyrBilyachat mentioned in comments, this will include your package.json file in the final bundle file.


Add this step to your build (ie Jenkins-Job):

echo export const version = { number: '%SVN_REVISION%' } > src\version.ts

You can access the number like this:

import { version } from "../version";

export class AppComponent {
    constructor() {
        console.log("MyApp version " + version.number);
    }
}

This solution is + lightweight, + easy to read, + robust.


  1. Install plugin npm install replace-in-file --save-dev
  2. Add to prod environment src/environments/environment.prod.ts new property

    export const environment = {
        production: true,
        version: '{BUILD_VERSION}'
    }
    
  3. Add build file replace.build.js to root of your folder

    var replace = require('replace-in-file');
    var buildVersion = process.argv[2];
    const options = {
        files: 'src/environments/environment.prod.ts',
        from: /{BUILD_VERSION}/g,
        to: buildVersion,
        allowEmptyPaths: false,
    };
    
    try {
        let changedFiles = replace.sync(options);
        console.log('Build version set: ' + buildVersion);
    }
    catch (error) {
        console.error('Error occurred:', error);
    }
    
  4. add scripts to package.json

    "updateBuild": "node ./replace.build.js"
    
  5. Use environment.version in your app

  6. Before build call npm run updateBuild -- 1.0.1

PS. You must always remember that {BUILD_VERSION} is never committed.

PS. I wrote a bit better solution in my blog

PS.3 as @julien-100000 mentioned you should not commit environment.prod.ts with updated version. Version update must happen only in build process. And should never be committed.