Error TS6059 in Angular monorepo: The file 'ng-youtube-api.service.ngtypecheck.ts' is not located within the 'rootDir' directory. The 'rootDir' should include all source files

Creating multiple Angular libraries/packages is crucial for organizing code efficiently. In this case, I have developed three distinct packages:

  • @example/ng-youtube-player: includes a YoutubePlayerComponent and the associated YoutubeApiService
  • @example/ng-dailymotion-player: consists of a DailymotionPlayerComponent along with its corresponding DailymotionApiService
  • @example/ng-vimeo-player: houses a VimeoPlayerComponent alongside the necessary VimeoApiService

As part of my ongoing development process, I aim to construct a new library featuring a universal VideoPlayerComponent. To achieve this, I intend to utilize only the services provided by the YoutubeApiService, DailymotionApiService, and VimeoApiService packages. Separating these service classes from the complete libraries will streamline installations and minimize unnecessary component inclusion.

Although angular's tree-shaking functionality theoretically prevents unused components from being bundled into the application, I prefer keeping dependencies isolated for clarity.

In an attempt to realize this vision, I ventured into setting up a monorepo containing two libraries and a testing application. However, encountering build failures upon referencing a service from another library prompted me to create a simplified workspace for issue replication:

git clone https://github.com/PieterjanDeClippel/angular-monorepo-test
cd angular-monorepo-test
npm install
ng build @mintplayer/ng-youtube-api
ng build @mintplayer/ng-youtube-player
ng build ng-youtube-player-demo

# All projects compile successfully
# Now go to the NgYoutubePlayerComponent and uncomment the injection parameter in the constructor (line 16)

ng build @mintplayer/ng-youtube-player

The build subsequently failed, inundating the console with numerous errors similar to the following:

✖ Compiling with Angular sources in Ivy partial compilation mode.
projects/mintplayer/ng-youtube-api/src/lib/ng-youtube-api.service.ts:1:1 - error TS6059: File 'C:/Users/user/source/repos/Tmp/mintplayer-ng-youtube-player/projects/mintplayer/ng-youtube-api/src/lib/ng-youtube-api.service.ngtypecheck.ts' is not under 'rootDir' 'C:\Users\user\source\repos\Tmp\mintplayer-ng-youtube-player\projects\mintplayer\ng-youtube-player\src'. 'rootDir' is expected to contain all source files.
1 import { Injectable } from '@angular/core';
 
projects/mintplayer/ng-youtube-api/src/public-api.ts:1:1 - error TS6059: File 'C:/Users/user/source/repos/Tmp/mintplayer-ng-youtube-player/projects/mintplayer/ng-youtube-api/src/public-api.ngtypecheck.ts' is not under 'rootDir' 'C:\Users\user\source\repos\Tmp\mintplayer-ng-youtube-player\projects\mintplayer\ng-youtube-player\src'. 'rootDir' is expected to contain all source files.

Evidently, two primary issues emerged during this process:

  1. Each project must be built separately in the correct sequence
  2. Libraries cannot directly utilize services from other libraries

Despite exploring related questions on this matter, such as 'rootDir' is expected to contain all source files, definitive solutions remain elusive.

Code

To examine this conundrum further, refer to my test code hosted here. Detailed instructions for reproducing the issue are available within the aforementioned repository. Key modifications made to the root tsconfig.json file are outlined below:

{
  ...
  "compilerOptions": {
    ...,
    "paths": {
      "@mintplayer/ng-youtube-api": [
        "projects/mintplayer/ng-youtube-api/src/public-api.ts"
      ],
      "@mintplayer/ng-youtube-player": [
        "projects/mintplayer/ng-youtube-player/src/public-api.ts"
      ]
    }
  }
}

While successful integration between a library and application has been achieved without complications (as evidenced in the initial repositories mentioned at the beginning), challenges persist when attempting cross-library communication. Seeking guidance on resolving this deadlock and establishing a unified workspace housing two libraries and a test application is paramount.

Answer №1

Have you ever come across issues with nx causing errors in your project?

I recently faced a similar problem that had me puzzled for a while.

Nx wasn't building correctly and kept throwing errors related to one of my referenced projects, @scope1/lib2, claiming its .ts files were outside the referencing project's scope. Strangely, even though @scope1/lib2 was listed in the dep-graph, there was no clear dependency arrow connecting it to the referencing library.

After some troubleshooting, I found a simple solution:

rm -rf node_modules/.cache

It seems like Nx had cached something incorrectly, as after clearing the cache, the dep-graph updated properly and the build process worked smoothly again.

Answer №2

Perhaps I am a bit behind, but I recently encountered a similar issue while using Angular CLI in my workspace. After extensive research and delving into the Typescript documentation on Module Resolution, I think I have finally grasped the problem:

Path mapping is a common practice for Angular Libraries, especially when employing a secondary entry-points strategy. However, its functionality can be quite intricate. Things become even more perplexing when managing multiple libraries within the same workspace: sometimes the IDE throws errors unexpectedly, while other times everything seems fine until it breaks during compilation or building.

The crux of the issue lies in the fact that consumers require the compiled versions of the libraries to function correctly, necessitating them to reference the dist folder. My workaround involved:

  • Maintain development-time mappings (resolving to projects/...) in the main tsconfig.json file
  • Incorporate mappings to built artifacts in the tsconfig used for constructing the consumer library (outlined in angular.json configurations)

This approach appeased both the IDE and ng-packagr – everyone's happy!

Cheers to smooth sailing from now on!

Answer №3

Encountering the cryptic error message "....is not under 'rootDir'. ..." in an NX workspace may signal that you have imported a library (lib1) into another buildable library (lib2), causing lib2 to be unable to access lib1. This type of cross-library import is not supported by Nx, leading to this misleading error message.

To resolve this issue, simply remove the imported interfaces or classes from lib1 within lib2, and functionality should be restored.

For further insights, refer to this Github issue: https://github.com/nrwl/nx/issues/602

You can also explore a potential solution here: https://github.com/nrwl/nx/issues/602#issuecomment-908064982

Answer №4

In my experience with an angular/nx monorepo, I encountered a cache problem that I was able to resolve by executing

rm -rf node_modules/.cache

Answer №5

After spending multiple days trying to figure out what was causing this bug, I finally discovered that the error originated from Webstorm importing the model file with an incorrect path.

import { Invoice } from "libs/invoicing/src/lib/invoice/invoice.model";

The correct import should have been:

import { Invoice } from "../../../../invoice/invoice.model";

Answer №6

In my experience (working with NX v16.10.0), I encountered a discrepancy between the library name specified in my tsconfig.base.json file and the actual name present in the generated package.json file.

To illustrate, I had modified the library name in the tsconfig.base.json to be @lib/shared-new-feature, whereas the package.json was still showing a name of new-feature.

Answer №7

I encountered a similar error message due to a secondary entry point library. I opted to utilize NX CLI in creating a library as a secondary entry point for the existing one (which served as a testing library). This led me to include the root library into the testing library, resulting in a relative import.

import { CustomService } from '../../../src

To resolve this issue, I modified it to:

import { CustomService } from '@myorg/libname'

Just a friendly reminder - make sure to read through all responses on a question and not just focus on the most highly upvoted ones! :D

Answer №8

It appears that you may be trying to import a module from a location outside of your library's designated root directory, typically denoted as src.

For instance:

// src/index.js
import something from '../../outside-module' //<-- located outside the rootDir

Answer №9

It seems like NX is the way to go: . Building an angular library becomes a breeze when you start with an NX project.

npm install -g @angular/cli@latest
npm install -g nx
npx create-nx-workspace
cd mycompany-ng-youtube-player

Create a youtube player library:

nx g @nrwl/angular:lib mycompany-ng-youtube-player --buildable --publishable --import-path @mycompany/ng-youtube-player

Define your package name and version in the package.json:

{
  "name": "@mycompany/ng-youtube-player",
  "version": "1.0.0",
  ...
}

Create a library for the IFrame API:

nx g @nrwl/angular:lib mycompany-ng-youtube-api --buildable --publishable --import-path @mycompany/ng-youtube-api

Specify your package name and version in the package.json:

{
  "name": "@mycompany/ng-youtube-api",
  "version": "1.0.0",
  ...
}

Create a component in the @mycompany/ng-youtube-player:

cd .\libs\mycompany-ng-youtube-player\src\lib
nx g component ng-youtube-player --project=mycompany-ng-youtube-player --module=mycompany-ng-youtube-player --export

Create a service in the @mycompany/ng-youtube-api:

cd ..\..\..\mycompany-ng-youtube-api\src\lib
nx g service ng-youtube-api --project=mycompany-ng-youtube-api

Add the package dependency to the package.json of the player:

{
  ...,
  "peerDependencies": {
    "@mycompany/ng-youtube-api": "~3.0.0",
    ...
  }
}

After that, make necessary code adjustments.

To build and run the application:

npm run nx run-many -- --target=build --projects=ng-youtube-player-demo --with-deps
npm run nx serve -- --open

A Word of Caution

If considering NX, keep these points in mind:

  • New Angular release (v14)
  • Your library users await a @angular/core@v14 compatible version
  • NX awaits Angular 14 support
  • NX waits for jest-preset-angular to add v14 compatibility
  • ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm encountering an issue where the npm install process is getting stuck while attempting to extract the xxxx package

When running the sudo npm install command on my local machine, everything works fine. However, once I pulled the code into an EC2 Ubuntu machine, the npm install process gets stuck at a certain point. The output shows "sill doParallel extract 1103" and I ...

Using TypeScript for abstract methods and polymorphism

What do I need to fix in order for this code to function properly? abstract class Animal { // No constructor ... public abstract me():Animal; } class Cat extends Animal { constructor() { super(); } // Why does this no ...

Uncovering the secrets of incorporating axios with Vue in Typescript

I'm facing difficulties while trying to incorporate axios into my Vue project using Typescript. Below is a snippet of my main.ts file: import axios from 'axios' Vue.prototype.$axios = axios axios.defaults.baseURL = 'http://192.168.1.22 ...

Preventing Redundancy in Angular 2: Tips for Avoiding Duplicate Methods

Is there a way I can streamline my if/else statement to avoid code repetition in my header component? Take a look at the example below: export class HeaderMainComponent { logoAlt = 'We Craft beautiful websites'; // Logo alt and title texts @Vie ...

From Angular to C#: Converting DatePickers to DateTime objects

I am encountering an issue when trying to send a request with two dates selected in angular-material date pickers to the server. The network appears to be sending them correctly, but when they reach the controller, their value defaults to DateTime default& ...

Troubleshooting spacing problems in Angular Material tables

I'm attempting to utilize an Angular Material table in the following way: <div class="flex flex-col pb-4 bg-card rounded-2xl shadow overflow-hidden"> <table mat-table class="" [dataSource]="$candidates ...

Mastering TypeScript debugging in Visual Studio Code with automatic restart

Currently, I am in the process of setting up a TypeScript project using Node. For debugging my main.ts file in Visual Studio Code, I have configured the launch.json as follows: { "type": "node", "request": "launch", "name": "Star ...

Issue with Angular 2: MaterializeCSS module not loading correctly when using routing

I am currently incorporating MaterializeCSS into my Angular project. It appears that materialisecc.js and/or jquery.js are loaded with routing, causing the need to reload each page of the app for it to function properly. This issue is affecting the overall ...

The Typescript ternary operation issue indicating that the condition is expected to always result in 'false'

I encountered a Typescript error that says: This condition will always return 'false' since the types 'TItem' and '"Chat"' have no common values. TS2367 Here is the code snippet causing the error: const { menu } = stat ...

Encountering issues with Sequelize Typescript on delete cascade functionality

One issue I encountered is related to the FK relationship between Group and GroupAttendee. Whenever I try to call Group.destroy(), a foreign key constraint failure exception regarding the GroupAttendee entries pops up. I know how these constraints work at ...

Developing a firestore query using typescript on a conditional basis

I've encountered an issue while attempting to create a Firestore query conditionally. It seems like there's a TypeScript error popping up, but I can't seem to figure out what's causing it. Here's the snippet of my code: const fetch ...

Getting into nested information in a JSON string using TypeScript

I need help accessing the data values (data1, data2, and date) from this JSON structure. I would like to store these values in an array that can be sorted by date: { "07" : { "07" : { "data1" : "-1", "data2" : "test", "date" : "1995-07-07" ...

What is the proper error type to use in the useRouteError() function in react-router-dom?

In my React project, I am utilizing the useRouteError() hook provided by react-router-dom to handle any errors that may arise during routing. However, I'm uncertain about the correct type for the error object returned by this hook. Currently, I have ...

Substitute the existing path with an alternative route

To move to a different route in Angular 2.0, we typically use route.navigate( [ 'routeName' ] ). However, this approach adds the current route to the browser's history. Is there a technique available to substitute the current route in the ...

Importing multiple modules in Typescript is a common practice

I need to include the 'express' module in my app. According to Mozilla's documentation, we should use the following code: import { Application }, * as Express from 'express' However, when using it in TypeScript and VSCode, I enc ...

What is the correct data type for the vuex store that is passed to the vuex plugin when it is being initialized?

Here is how the store initialization process is currently being implemented: /* Logic */ import Vue from 'vue' import Vuex, { StoreOptions } from 'vuex' Vue.use(Vuex) const DataManager = new UserDataManager() type RootStateType = { ...

Is there a way to access a component instance from an event handler in Angular?

I am facing a challenge with a dynamic component where I require a reference in the event handler function. Due to them being dynamic and placed inside templates, I cannot utilize ViewChild. <custom-example #refExample (click)="onCustom(refExample) ...

Customizing Array.of() in Typescript for a specialized 2D array class that inherits from Array

I am working on creating a custom Array2D class by extending the Array class in JavaScript. My goal is for the constructor to accept any number of arguments, each representing an array of type T. Here is the current implementation: class Array2D<T> ...

Developing a self-contained application with individual components in Angular 16: the ultimate guide to importing singleton services and components

I have been working on a course that does not utilize the latest Angular 16 features. As I progress, I am making an effort to convert it to use standalone components. The App.module.ts in the course project currently has the following structure: @NgModule ...

Leveraging a custom pipe along with a ternary operator in an *ngFor loop

Having troubles with a custom pipe using ternary operator in *ngFor and encountering errors. Seeking assistance to resolve the issue. Here is the HTML code snippet: <div *ngFor="let x of y | limitTo: y.limit ? y.length : 10"> The truncate.pipe.ts ...