Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pull application version (or import package.json file)? Google does not help :(

In my Angular application, I'd like to display the version from the package.json file.

I know that to import it I need to allow importing json and for this tsconfig.json file needs to get a few extra lines:

{
  "compilerOptions": {      
    "module": "commonjs",
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "moduleResolution": "node"
  }
}

I did this, but after that when I import json file in my component class:

import { myPackage } from '../../../package.json';

I still get an error:

Cannot find module '../../../package.json'. Consider using '--resolveJsonModule' to import module with '.json' extension.ts(2732)

And problem is not with path as I put another simple json file to the same folder but getting the same error.

I've googled and seen many examples that speak about '--resolveJsonModule', but it seems like I do all what's needed... but it still does not work.

I also restarted VScode and angular service - it did not help.

I use Angular 10.0.11 and TS 3.9.7

Please advise! Thanks!

like image 570
Budda Avatar asked Jun 08 '26 14:06

Budda


2 Answers

In order to access the package.json information in angular, you need to do 3 things

  1. In your tsconfig.json, you need to enable resolveJsonModule option that is present in the compilerOptions like
    compilerOptions": {
         ......
         "resolveJsonModule": true
         ......
    }
  1. After that, you can rerun npm start in your terminal.

  2. Once you have rerun npm start, you will be able to access all the package.json variables inside the component as

import * as  packageJson from 'package.json';
......
export class AppComponent {
      ......
      version = packageJson.version;
      ......
}
like image 117
deepak thomas Avatar answered Jun 10 '26 04:06

deepak thomas


Deepak posted an almost proper answer, but for some reasons it did not work to me. Though, referenced answer (https://stackoverflow.com/a/48869478/6904274) has comments that actually helped.

In my case, the Angular application had more than just tsconfig.json, and to be able to import JSON files I had to modify other 'flavours': base, spec, and app. And each is responsible for their own thing. Obviously, to have that import work in components under tests, I need to add it to 'spec'. But, better to just 'base'.

like image 24
Budda Avatar answered Jun 10 '26 02:06

Budda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!