80

I want to have a timestamp or build number somewhere on my Angular2 App so I can tell if a user is using an old cached version or not.

How to do this with AngularCLI in Angular2 at AOT compile/build time?

15 Answers 15

82
  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.

Sign up to request clarification or add additional context in comments.

14 Comments

Thanks, that is what I was looking for. A few nice enhancements would be to generate a timestamp or autoincrement the build number (instead of having to input it).
@Rodney I actually just thought about that. Will do it and write in my blog :)
replace-in-file module has updated their options. Should use const options = { files: 'src/environments/environment.prod.ts', from: /{BUILD_VERSION}/g, to: buildVersion };
Actually the app version is anyway stored in package.json. Is there any way to use that?
One suggestion for those who do not want to care of not committing environment.prod.ts` by accident you can change regex expression. Here is an example and I added a build timestamp as well. let const buildVersionOptions = { files: 'src/environments/environment.prod.ts', from: /version:.*/gm, to: `version: '${buildVersion}',`, allowEmptyPaths: false, }; const timeStampOptions = { files: 'src/environments/environment.prod.ts', from: /buildTimestamp:.*/gm, to: `buildTimestamp: '${new Date().toISOString()}',`, allowEmptyPaths: false, };
|
26

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.

3 Comments

Which jenkins job? There are different CI solutions with no jenkings as well.
@Rantiev You have a point with that. However this simple approach should work with almost any build environment (maybe with slightly modified shell script). I updated my post.
This is the simplest and best solution. I used following command in my case echo "export const RunTimeFile = { buildtime:new Date('$(date -Is)') };" | tee src/environments/runtime-file.ts
23

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.

6 Comments

Awesome but here is one question which bother me. How tree shaking is working with require ?
@VolodymyrBilyachat I'm not sure if I understand this well, but tree shaking is about removing unused codes. I found this link which may be related: Angular Tree Shaking. Read the title "Why Typescript 2 is Needed"
Ok let me ask you other question. Have you looked in minified scripts after you build your application ?
@VolodymyrBilyachat No. What should I look for?
Reason I ask about how require works with tree shaking is because basically its injecting everything to your bundle. So if you do require package.json you should understand that WHOLE content of this file will be bundled into your min scripts. If you fine with that then its fine. And yes your link is totally unrelated to my question
|
10

May be a bit late for the discussion, but hopefully I can help someone else looking at the same problem.

I have written a small npm package called angular-build-info which sums up some information about the current build such as a build timestamp, the git user which built the app, a shortened commit hash and the apps version from your projects package.json file.

Implementing the package is also pretty easy, it creates a build.ts file under src/build.ts which you can then import in your Angular app and display the information anywhere.

An example of implementing it could look as follows: (app.component.ts)

import { Component } from "@angular/core";
import { buildInfo } from "../build";
import { environment } from "../environments/environment";

@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"]
})
export class AppComponent {
    constructor() {
        console.log(
            `\n%cBuild Info:\n\n%c ❯ Environment: %c${
                environment.production ? "production 🏭" : "development 🚧"
            }\n%c ❯ Build Version: ${buildInfo.version}\n ❯ Build Timestamp: ${
                buildInfo.timestamp
            }\n ❯ Built by: ${buildInfo.user}\n ❯ Commit: ${buildInfo.hash}\n`,
            "font-size: 14px; color: #7c7c7b;",
            "font-size: 12px; color: #7c7c7b",
            environment.production
                ? "font-size: 12px; color: #95c230;"
                : "font-size: 12px; color: #e26565;",
            "font-size: 12px; color: #7c7c7b"
        );
    }
}

which would output: link to console screenshot

I hope this will help someone! :)

1 Comment

nice package but I don't want to add another dependency to my project for this simple functionality.
9

I solved this by appending a comment at the end of index.html with the last commit hash. For example:

ng build --prod

git rev-parse HEAD | awk '{print "<!-- Last commit hash: "$1" -->"}' >> dist/index.html

You can then do a "View Source" in the browser, look at the bottom of the HTML, and see the deployed version of your app.

This of course assumes that you use git as the versioning system. You could easily change git rev-parse HEAD with any other command that outputs a unique version.

5 Comments

My understanding of 'build' and 'build number' are that they are not equivalent to a commit - there could be many builds before a commit.
I used your approach and doing: date/T >> dist\index.html (Gives me info when the last build was created) Working Great for me!
Thanks for this trick. I was about to ask a question here then stumbled upon your answer.
This was very helpful. I wanted to add a build date as well, so I used the following: printf '<!-- Last commit hash:%s Build Date:%s -->\n' "$(git rev-parse HEAD)" "$(TZ='America/New_York' date)"
Be careful when altering index.html in your build output if you have a PWA with the Angular Service Worker. I found that changing index.html can disrupt the checksum integrity expected by the NGSW. This caused an issue where my app was not being cached properly, and it repeatedly attempted to reinstall the PWA each time. Just a heads-up to save others from the same headache! :-)
9
  1. Create simple js file createBuildDate.js

    for example:

const { writeFileSync } = require('fs');
const { join } = require('path');

const ASSETS_FOLDER = 'src/assets'; // Define the assets folder name
const TIME_STAMP_PATH = join(__dirname, ASSETS_FOLDER, 'buildDate.json');

const createBuildDate = {
buildTime: new Date()
};

// Ensure the assets folder exists (if it doesn't, create it)
const fs = require('fs'); // Import fs again to use mkdirSync.

if (!fs.existsSync(join(__dirname, ASSETS_FOLDER))) {
fs.mkdirSync(join(__dirname, ASSETS_FOLDER), { recursive: true });
}

writeFileSync(TIME_STAMP_PATH, JSON.stringify(createBuildDate, null, 2));
  1. Edit script in package.json

    "build": "node src/environments/createBuildDate.js && ng build"
    

    or you can use prebuild

  2. Edit tsconfig.json

    "resolveJsonModule": true,
    
  3. Import json in component and use, e.g.

import buildInfo from '../assets/buildDate.json'

2 Comments

Could you please say where should "resolveJsonModule": true be in tsconfig.json? My file doesnt have this entry.
Hi! compilerOptions block
6

I looked at other solutions, but I have not been convinced by either using yet another package or generating a JSON (because the JSON is not exactly in the app). Also, I did not want to bother with uncommitted changes like in the accepted answer of this thread.

I end-up by making a tiny bash script that replaces automatically a string located somewhere in my App with the version got from GIT + the DateTime of the build.

Now when I build my app, I just need to execute the following script:

latesttag=$(git describe --tags)
now=$(date +'%a %y-%m-%d %H:%M')

sed -i '' "s/build_info/$latesttag/g" ./src/app/pages/home/user-preference/user-preference.component.html
sed -i '' "s/build_time/$now/g" ./src/app/pages/home/user-preference/user-preference.component.html

ng build --prod;

sed -i '' "s/$latesttag/build_info/g" ./src/app/pages/home/user-preference/user-preference.component.html
sed -i '' "s/$now/build_time/g" ./src/app/pages/home/user-preference/user-preference.component.html

And in my file user-preference.component.html

<footer class="footer mt-auto">
    <div class="container text-center">
        Build: build_info - build_time
    </div>
</footer>

2 Comments

This is such a great solution, no dependencies, easy to integrate into build steps.
Thanks! Another advantage of this approach is that it can be integrated with other deployment actions. In my case, I need to generate a zip folder for the project implementation team, thus I added: zip -rq ... ... ; scp .... :)
3

Just for reference, here is a platform-independent version of slartidan's answer. The timestamp is updated during build using a node.js script (bin/update-timestamp.js).

bin/update-timestamp.js

#!/usr/bin/env node
'use strict';

const fs = require('fs');
const stamp = new Date().toISOString();
fs.writeFileSync('./src/app/timestamp/Timestamp.ts', `export class Timestamp { public static readonly stamp = '${stamp}'; }`);

package.json

{
  "scripts": {
    "build": "node ./bin/update-timestamp.js && ng build --prod",
  },
}

app.component.ts

import {Timestamp} from './timestamp/Timestamp';

export class AppComponent {

  constructor() {
    console.log("timestamp", Timestamp.stamp);
  }
  
}

Comments

2

Starting Angular 19, you can pass --define KEY=VALUE to pass values to the application at build time without going through files.

It's documented here.

Comments

1

I wanted to share my approach as none of the mentioned solutions worked for me. My requirements were avoiding adding generated version information to git, not installing extra dependencies, and not altering the /dist output, as it disrupts checksum integrity for Angular NGSW PWAs.

Here’s a quick summary of my solution:

  1. Create version.ts in src/environments/:

    // src/environments/version.ts
    export const version = '0.0.0-development';
    export const buildDate = new Date().toISOString();
    export const commitHash = 'development';
    
  2. Node.js Script update-version.js for Version Info:

    const fs = require('fs');
    const execSync = require('child_process').execSync;
    
    const packageJson = require('./package.json');
    const commitHash = execSync('git rev-parse HEAD').toString().trim();
    const buildDate = new Date().toISOString();
    
    const content = `
    export const version = '${packageJson.version}';
    export const buildDate = '${buildDate}';
    export const commitHash = '${commitHash}';
    `;
    
    fs.writeFileSync('./src/environments/version.prod.ts', content);
    
  3. Prebuild Script in package.json:

    "scripts": {
      "prebuild": "node update-version.js"
    }
    
  4. File Replacement in angular.json:

    "fileReplacements": [
      {
        "replace": "src/environments/version.ts",
        "with": "src/environments/version.prod.ts"
      }
    ]
    
  5. Ignore version.prod.ts in .gitignore.

For a working example of this solution, visit this GitHub repository.

Comments

0

If you want to log/display not only the version number but also information from git (like the hash, tag, etc) you can consider using a custom schematic for the angular-cli that I created. Adding it to your Angular 8+ Application is as simple as executing ng add @w11k/git-info

For further Documentation and insights you can look at the documentation available at https://github.com/w11k/angular-git-info

Comments

0

Executing bash/shell commands inside npm scripts might be hard if you want to pass arguments, expand variables/functions etc.

So maybe the simplest solution would be to leverage javascript's string interpolation which is excellent, and the simplest file append operator >> of unix based systems :

package.json

  "build": "ng build --prod && node mypostbuildscript.js >> dist/index.html"

mypostbuildscript.js

console.log(`<!-- build timestamp: ${Date.now()} -->`);

Comments

0

Simple variation of @slartidan answer, but using npm scripts.

package.json:

  "scripts": {
    "build-number": "echo 'export const buildNumber = '$(date +%s)';' > ./src/environments/build-number.ts"
  }

environment.prod.ts:

import { buildNumber } from './build-number';

export const environment = {
  buildNumber,
  // 
  //
};

Comments

-4

Perhaps this is a good solution for someone.. https://medium.com/@amcdnl/version-stamping-your-app-with-the-angular-cli-d563284bb94d

What he describes is how to use your git data and have the last commit hash as build number.

By adding a postinstall step in your package.json a file will be generated when running the install script.

Comments

-6

I think for your case: ng build or ng serve add in environment.ts:

export class environment {
  production: false,
  buildTimestamp: new Date()
}

Then in your component:

import { environment } from 'src/environments/environment'; // or path to your environment.ts file

...

const buildTimestamp = environment.buildTimestamp;

This is what I was looking for.

1 Comment

This does not keep the timestamp of the build. This will update every time the page has loaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.