How to get the value from package.json file angular2+

I have scenario like get the version number in package.json file in the application. And print in the app.component.html file as application version number. How to import package.json file in the components.

There’s a few ways:

  1. Move the package.json file into the assets before build-time automatically using a script.
  2. Directly import the json file into the Angular client-code by updating tsconfig itself so it can load JSON files (here’s an article on importing json files in Angular as a starting point)
  3. Create a custom build-script that reads your package.json and saves this value into a file in assets that you load at runtime or load directly like #2. Don’t save this build-time script to git as its something you only want before build time. So every time you deploy, your app includes the version from the package.json (and maybe other metrics), but nothing else.

However I’m not sure you want to expose your entire package.json to the client-side like this. This could be like giving a menu to hackers who can use outdated packages to exploit. This is a stretch, but not really something I’d do just to show a version number. So this really leaves #3 as the most “secure” option rather than just giving everyone all the packages+versions to the client.

I personally using take #3 so I can check on which version is deployed, but this requires some kind of automation to run this extra script before/during build-time.

Thanks for the clear explanation @bradtaniguchi

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.