Knowing the exact version of your Angular app can be really helpful. This article will teach you how to add your app’s package version, git commit hash, and build date to your builds. You’ll also learn how to access this information within your Angular app.
-
Create a File for Version Information
- Make a file named
version.ts
in thesrc/environments/
folder. - Add placeholders for the app version, build date, and commit hash, like this:
// src/environments/version.ts export const version = '0.0.0-development'; export const buildDate = Date.now(); export const commitHash = 'aaaaaa';
- Make a file named
-
Then, you can use this version information in your Angular code. Here’s how you might do it:
import { Injectable } from '@angular/core'; import { version, buildDate, commitHash } from 'src/environments/version'; @Injectable({ providedIn: 'root' }) export class VersionService { getVersion(): string { return `Version ${version}, commit ${commitHash}, built at ${buildDate}`; } }
2. Write a Script to Update Version Information
- Make a file called
update-version.js
in your project’s main folder. -
This script will automatically fill in the real version and commit hash using Node.js code. Here’s an example:
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. Add a Prebuild Script to Your Project
- In your
package.json
file, add aprebuild
script in the “scripts” section. -
This script should run
node update-version.js
before each build. Yourpackage.json
should include something like this:"scripts": { "prebuild": "node update-version.js" }
4. Update Your Build Configuration
-
In the
angular.json
file, make a change to useversion.prod.ts
instead ofversion.ts
when you build your app. Here’s how you can set it up:"fileReplacements": [ { "replace": "src/environments/version.ts", "with": "src/environments/version.prod.ts" } ]
5. Ignore the Generated Version File
- If you want, you can add
version.prod.ts
to your.gitignore
file. This keeps the automatically generated file out of your code repository.