1

I'm building an angular library and got stuck trying to access package.json file in the integrating app.

My purpose is to read the app-version variable from the integrating app.

this is what I thought:

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


@Injectable({
  providedIn: 'root'
})
export class AppVersionService {

  private version: string = version;

  getVersion() {
    return this.version;
  }
}

Logically I'm getting this error:

ERROR: error TS6059: File 'C:/.workspace/app-versioning/package.json' is not under 'rootDir' 'C:\.workspace\app-versioninge\projects\app-versioning\ng-core'. 'rootDir' is expected to contain all source files.

P.S: I need to load just the app-version variable into the browser, not the whole package.json file.

Any Ideas, Thanks!

Taher
  • 258
  • 2
  • 15

1 Answers1

1

You can use require to obtain the file package.json.

One good and clean practice is to exported using the environment. To do this just request the file in environment.ts, and export the data you want, something like this

const packageJson = require('../../package.json');
export const environment = {
  ..
  version: packageJson.version
}

Of course you have to correct the number .. to the file.

UPDATE:

angular-ngrx-material-starter

This angular starter project include interesting tools for development and several good practices including the one I mention in the answer. I thought it is was worth to add it to the answer.

cabesuon
  • 4,860
  • 2
  • 15
  • 24
  • Thanks! But this loads the whole content of package.json. I need just the app-version variable. – Taher Mar 16 '20 at 13:28
  • But is a json file, you can't access just one property, you need to load the whole file and then keep the things you need. – cabesuon Mar 16 '20 at 13:51
  • It can be done with import. take a look here: https://stackoverflow.com/questions/34907682/how-to-display-the-app-version-in-angular – Taher Mar 16 '20 at 14:32
  • I see .. add the structure of you project to the question please – cabesuon Mar 16 '20 at 14:50