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?
npm install replace-in-file --save-devAdd to prod environment src/environments/environment.prod.ts new property
export const environment = {
production: true,
version: '{BUILD_VERSION}'
}
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);
}
add scripts to package.json
"updateBuild": "node ./replace.build.js"
Use environment.version in your app
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.
replace-in-file module has updated their options. Should use const options = { files: 'src/environments/environment.prod.ts', from: /{BUILD_VERSION}/g, to: buildVersion };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, }; 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.
echo "export const RunTimeFile = { buildtime:new Date('$(date -Is)') };" | tee src/environments/runtime-file.tsThere's no need to replace-in-file.
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
Note: As @VolodymyrBilyachat mentioned in comments, this will include your package.json file in the final bundle file.
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! :)
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.
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! :-)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));
Edit script in package.json
"build": "node src/environments/createBuildDate.js && ng build"
or you can use prebuild
Edit tsconfig.json
"resolveJsonModule": true,
Import json in component and use, e.g.
import buildInfo from '../assets/buildDate.json'
"resolveJsonModule": true be in tsconfig.json? My file doesnt have this entry.compilerOptions blockI 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>
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);
}
}
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.
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:
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';
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);
Prebuild Script in package.json:
"scripts": {
"prebuild": "node update-version.js"
}
File Replacement in angular.json:
"fileReplacements": [
{
"replace": "src/environments/version.ts",
"with": "src/environments/version.prod.ts"
}
]
Ignore version.prod.ts in .gitignore.
For a working example of this solution, visit this GitHub repository.
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
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()} -->`);
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,
//
//
};
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.
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.