Get App Name And Version In Angular

How to read or display the name and version of your application in Angular without duplicating these information

Image for post
Image for post
Photo by Joe Chau on Unsplash

Import JSON File In TypeScript

We don’t want to duplicate the app’s name or version, that’s why I suggest that we read these from our package.json . In order to import JSON files in TypeScript, we need to instruct the compiler to accept such type of data. To do so, in our tsonfig.json we turn the option resolveJsonModule to true .

"compilerOptions": {
"resolveJsonModule": true
},

Environment Variables

A convenient way to handle environment variables is possible, out of the box, in Angular through the use of the multiples environment.ts files. That’s why we enhance these to “inject” our application’s name and version.

import {name, version} from '../../package.json';

export const environment = {
production: true,
name,
version
};

AngularFire Analytics

If like me, you use AngularFire and would like to track these information, proceed as the following in your app.module.ts . Note that in the spinet I also set anonymize_ip to true , as it should, in my humble opinion, always be the case.

import {AngularFireAnalyticsModule, 
APP_NAME, APP_VERSION, CONFIG}
from '@angular/fire/analytics';
import {environment} from '../environments/environment';@NgModule({
providers: [
{
provide: CONFIG,
useValue: {
allow_ad_personalization_signals: false,
anonymize_ip: true
}
},
{provide: APP_NAME, useValue: environment.name},
{provide: APP_VERSION, useValue: environment.version}
]
})
export class AppModule {
}

Summary

I’m agree, this isn’t the deepest and longest blog post I have ever written but I hope it might be useful anyway to someone in the future, one never knows 😄.

Written by

Freelancer by day | Creator of DeckDeckGo by night | Organizer of the Ionic and IndieHackers Zürich Meetup

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store