It’s common for applications to display what version of the application is currently being used. For example, in browsers, you can go to their About page and see what browser version you’re using. Let’s learn how to display your package.json version in your Angular application!
resolveJsonModule
When working with Javascript modules, it’s common to import specific pieces you need using an import statement.
import { Component } from '@angular/core';
We’d like to import the version value from the package.json file. However, that’s not possible at the moment. We need to tell Typescript to allow that to happen using the resolveJsonModule setting. In your tsconfig.app.json file, add the following under the compilerOptions property:
compilerOptions: {
...
"resolveJsonModule": true
...
}
Import Version
In the component where you’d like to display the version number, now you can import it successfully.
import { version } from 'path/to/package.json';
Make sure to import the version only. It can be dangerous to expose other information about your package.json file.
Create a variable in your component and assign it the version value you just imported.
export class AppComponent {
version = version;
}
Display Version
In your component’s html, place the variable where you want the version to appear.
Version: {{ version }}
Visit our website at https://nightwolf.dev and follow us on Facebook and Twitter!
Top comments (8)
Doesn't work in Angular 12.
Error: Should not import the named export 'version' (imported as 'version') from default-exporting module (only default export is available soon)
Try the following instead:
import pkg from 'path/to/package.json'
Then when you reference it in your component, use the following:
version = pkg.version;
This works, thanks.
However, with this approach you're copying the whole
package.json
in build dest, which might be unsecure.Correct, there are security implications when importing the whole package.json.
Another option is to add node to your types property in tsconfig. Then you can use require like the following:
version = require('path/to/package.json').version
But this also exposes
package.json
to dist, right?On your build pipeline, you could write a custom script that can extract necessary information from
package.json
and add it to new JSON file e.g.versionInfo.json
.Have the same file checked-in for local dev usage.
You can securely copy this and use this.
Excuse me, but copy what? Did you paste a code snippet I can't see?