For Angular 12 +,
Follow this steps:
Step 1:
We need to use the require
node function in our environment files, so we have to add node types to the compiler options. Open tsconfig.app.json and tsconfig.spec.json files (usually they are located under the ‘src’ folder), add “node” under compilerOptions -> types
...
"compilerOptions": {
"outDir": "../out-tsc/spec",
"module": "commonjs",
"types": [
"jasmine",
"node"
]
}
...
Note: Be sure to have included ‘@type/node’ as a dependency in your ‘package.json’ file.
Step 2:
Now open environment.ts (‘src\environments\environment.ts’) and create a property for holding the application version in environment variable as follows ( in our case this will be appVersion
) :
export const environment = {
appVersion: require('../../package.json').version + '-dev',
production: false
};
Be aware, the path to package.json must be calculated from the environment file’s location.
The require(‘../../package.json’).version will load the version number from the package.json file and + ‘-dev’ will add the ‘-dev’ suffix to it. The suffix isn’t a must, but this way you can identify witch environment file is used for running your application
Following the same approach we have to edit the production environment file as well. In the end the environment.prod.ts will look like this:
export const environment = {
appVersion: require('../../package.json').version,
production: true
};
Step 3:
Add version number to a component and show it in the application. For example:
import {Component} from '@angular/core';
import {environment} from '../environments/environment';
@Component({
selector: 'app-root',
template: `<h1>{{title}}</h1>
<h3>v{{currentApplicationVersion}}</h3>`
})
export class AppComponent {
title = 'Demo application for version numbering';
currentApplicationVersion = environment.appVersion;
}
const packageJson = require('../package.json')
. – Bugbaneimport {abc} from "some.json"
warns me whenabc
attribute exists in json? – Dexter