HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptangularCritical

How to display the app version in Angular?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
angularapphowdisplaytheversion

Problem

How do I display the app version in Angular application? The version should be taken from package.json file.

{
  "name": "angular-app",
  "version": "0.0.1",
  ...
}


In Angular 1.x, I have this html:



In Angular, this is not rendered as version number, but instead just printed as it is (` instead of 0.0.1`).

Solution

If you want to use/show the version number in your angular app please do the following:

Prerequisites:

  • Angular file and folder structure created via Angular CLI



Steps for Angular 6.1 (TS 2.9+) till Angular 11

  • In your /tsconfig.json (sometimes also necessary in /src/tsconfig.app.json) enable the following option (webpack dev server restart required afterwards):



"compilerOptions": {
      ...
      "resolveJsonModule": true,
      ...


  • Then in your component, for example /src/app/app.component.ts use the version info like this:



import { version } from '../../package.json';
    ...
    export class AppComponent {
      public version: string = version;
    }


When using this code with Angular 12+ you will probably get: Error: Should not import the named export 'version' (imported as 'version') from default-exporting module (only default export is available soon).
In this case please use the following code:

Steps for Angular 12+

  • In your /tsconfig.json (sometimes also necessary in /src/tsconfig.app.json) enable the following options (webpack dev server restart required afterwards):



"compilerOptions": {
      ...
      "resolveJsonModule": true,
      "allowSyntheticDefaultImports": true,
      ...


  • Then in your component, for example /src/app/app.component.ts use the version info like this:



import packageJson from '../../package.json';
    ...
    export class AppComponent {
      public version: string = packageJson.version;
    }


It's also possible to do step 2 in your environment.ts file, making the version info accessible from there.

Thx @Ionaru and @MarcoRinck for helping out.

This solution should not include the package.json contents when doing a production build - only the version number (checked w/Angular 8 and 13).

To be sure please check your generated main.#hash#.js file too!

Code Snippets

"compilerOptions": {
      ...
      "resolveJsonModule": true,
      ...
import { version } from '../../package.json';
    ...
    export class AppComponent {
      public version: string = version;
    }
"compilerOptions": {
      ...
      "resolveJsonModule": true,
      "allowSyntheticDefaultImports": true,
      ...
import packageJson from '../../package.json';
    ...
    export class AppComponent {
      public version: string = packageJson.version;
    }

Context

Stack Overflow Q#34907682, score: 458

Revisions (0)

No revisions yet.