'Import package.json in Angular Nx Library error

Issue description

When trying to import package.json in an Angular nx library, the following error appears at compile time (that is, when trying to build the library).

File 'test/package.json' is not under 'rootDir' 'test/libs/test/src'. 'rootDir' is expected to contain all source files.

Importing package.json in an Angular nx application renders no problems and works as expected.

What I have done

I have added "compilerOptions"."resolveJsonModule": true and "compilerOptions"."allowSyntheticDefaultImports": true in tsconfig.base (otherwise it doesn't support importing at all).

What I have tried

There are other topics around this on Stack Overflow, and I have tried all suggestions, but none seem to be about libraries and nothing worked anyways. I'm not sure whether this is an anti-pattern, a configuration problem, or an issue of nx that needs to be raised on Github.

Repro steps

  1. Run npx create-nx-workspace@latest test-workspace and follow through the steps to create an Angular application
  2. Within the project, run npx nx generate @nrwl/angular:library --name=test --buildable
  3. In tsconfig.base.ts, add the following:
  ...
  "compilerOptions": {
    ...
    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true
    ...
  },
  ...
  1. In test.module.ts, add the following:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import packageJson from 'package.json'; // <---------- add this

@NgModule({
  imports: [CommonModule],
})
export class TestModule {
  constructor() { // <-------------------------------- add this
    console.log(packageJson.version); // <------------ add this
  } // <---------------------------------------------- add this
}
  1. Building the library with npx nx build test fails with the rootDir error


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source