The directory designated as 'rootDir' should encompass all source files within it

In my Angular CLI workspace, I have two library projects named foo and bar. The issue arises when I try to build the second library, foo, as it fails with the following error:

Error TS6059: File '/code/projects/bar/src/lib/types.ts' is not located under 'rootDir' '/code/projects/foo/src'. The 'rootDir' should contain all source files.

Error: Error TS6059: File '/code/projects/bar/src/lib/types.ts' is not located under 'rootDir' '/code/projects/foo/src'. The 'rootDir' should contain all source files.

    at Object.<anonymous> (/code/node_modules/ng-packagr/lib/ngc/compile-source-files.js:53:68)
    at Generator.next (<anonymous>)
    at /code/node_modules/ng-packagr/lib/ngc/compile-source-files.js:7:71
    at new Promise (<anonymous>)
    at __awaiter (/code/node_modules/ng-packagr/lib/ngc/compile-source-files.js:3:12)
    at Object.compileSourceFiles (/code/node_modules/ng-packagr/lib/ngc/compile-source-files.js:19:12)
    at Object.<anonymous> (/code/node_modules/ng-packagr/lib/ng-v5/entry-point/ts/compile-ngc.transform.js:26:32)
    at Generator.next (<anonymous>)
    at /code/node_modules/ng-packagr/lib/ng-v5/entry-point/ts/compile-ngc.transform.js:7:71
    at new Promise (<anonymous>)

To recreate this error, I have set up a sandbox repository on GitHub available here. While attempting to simplify the code, I encountered this issue. By running npm run build on the rootDir-expect-all-source-files-error branch, you can experience the error firsthand. What could be the root cause of this problem? Is it related to a bug within ng-packagr, ngc, or tsc? Or is it just a configuration mishap?

Observations

Below are some modifications that allow the build to succeed. However, I am interested in understanding what is triggering the error in its current state.

bar.component.ts

Build Failure

export class BarComponent {

  list = this.barService.list();

  constructor(private barService: BarService) {}
}

Successful Build

Initiate the list property inside the constructor instead of inline

export class BarComponent {

  list;

  constructor(private barService: BarService) {
    this.list = this.barService.list();
  }
}

bar.service.ts

Build Failure

import { Injectable } from '@angular/core';
import { List, Item } from './types';

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

  private _list: List = [];

  constructor() { }

  add(item: Item): void {
    this._list.push(item);
  }

  list(): List {
    return this._list;
  }
}

Successful Build

Remove the specific data types

import { Injectable } from '@angular/core';

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

  private _list: any[] = [];

  constructor() { }

  add(item: any): void {
    this._list.push(item);
  }

  list(): any {
    return this._list;
  }
}

Answer №1

This issue seems to be related to the problem caused by the import types feature that was added in TypeScript 2.9. The rewiring of these imports is not done correctly, as indicated on line 3.

dist/bar/lib/bar.component.d.ts(5,11):

export declare class BarComponent implements OnInit {
    private barService;
    list: import("projects/bar/src/lib/types").Item[]; 
    constructor(barService: BarService);
    ngOnInit(): void;
}

In the generated dts file above,

list: import("projects/bar/src/lib/types").Item[];
should actually be something like import("./types").Item[];.

A workaround for this issue is to explicitly set the type instead of inferring it from your code.

In the bar.component.ts file, make the following change:

list = this.barService.list();

to:

list: Item[] = this.barService.list();

By doing this, you can eliminate the type import and ensure that the consuming library will compile successfully.

I have also looked into later versions of TypeScript, and while the problem still exists in TypeScript 3.0.1, it appears to have been resolved in the development version of TypeScript 3.1.0, specifically 3.1.0-dev.20180813.

Answer №2

Encountered a similar issue where the solution provided by @Agius did not resolve it for me.

In my situation, the project structure looked like this:

Angular Workspace
  - projects
      - lib1
      - lib2
  - src
      - test application

The problem arose when I moved a component from lib2 to lib1 using WebStorm's drag and drop feature. This action updated the references in lib2 to point to the source folder of lib1 instead of removing them completely. I forgot to clean up these unnecessary references in lib2 which caused compilation errors. Once I removed all references to the component in lib2, the library compiled successfully.

To fix this issue, I had to remove the references in:

  • public_api.ts
  • ./lib/lib2.module.ts

It's possible that there are additional references lingering in your project as well.

Answer №3

In my recent typescript project, I encountered an issue related to imports with a similar error message. After some troubleshooting, I managed to resolve it by adjusting the include value in the tsconfig.json file as shown below:

{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "ES2017",
    "noImplicitAny": true,
    "preserveConstEnums": true,
    "outDir": "./dist",
  },
  "exclude": ["node_modules", "**/*.test.ts"],
  "include": ["src"]
}

I hope this solution can be helpful for others facing a similar issue.

Answer №4

There seems to be an issue with the import statements, specifically where the import path is not being provided correctly.

For instance:

 import * from '../.././../tools1/tools2/tools/demo';

should actually be:

import * from '@tools/tools/demo';

In this scenario, @tools represents the root directory. Please note that the example path mentioned above is for illustration purposes only.

Answer №5

When working with , encountering a specific error may leave you scratching your head.

I personally faced a similar issue that seemed to be causing havoc...

The perplexing situation arose when nx refused to build correctly, bombarding me with errors related to a referenced project named @scope1/lib2 and its .ts files supposedly existing outside the referencing project... Interestingly, even though @scope1/lib2 was displayed in the dependency graph, there was no link showing connections between them...

But fear not, as I managed to find a solution:

rm -rf node_modules/.cache

My theory is that there must have been some mishap in the cache which hindered the correct display of dependencies. After clearing it out, the dep-graph finally reflected the linkage accurately, allowing for a successful build process.

Answer №6

If you encounter the error message "The file is not located under 'rootDir'..." in NX workspace, it may indicate that you have inadvertently imported a library1 into another buildable library2. Additionally, attempting to reference inc ts-config has proven unsuccessful for me...

Take a look at this helpful comment: https://example.com/a/12345678/9876543

Answer №7

While working on my NX Repo, I encountered an issue with the *.ngtypecheck.ts files that were being automatically generated by the @ngtools/webpack.

To resolve this issue, I had to eliminate the reference to implicitDependencies in the project.json file.

Here is an example of the project structure:

{
  "name": "icons"
}

And here is a project referencing the icons project:

{
  "name": "button",
  "implicitDependencies": ["!icons"]
}

By removing "!icons" from the list, the error was resolved.

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

The API request does not provide randomized results and does not show any display

I am facing an issue with a button that is supposed to fetch a random user from an API. When I retrieve all the users, the information is displayed correctly. However, when I try to select a user at random, it does not work as expected. Also, it seems to a ...

How can I use a custom pipe from an Angular library in my project?

I am encountering a problem when trying to import a custom pipe from an Angular library into the main app. This pipe is part of a custom library and I am using the static forRoot approach to load the library's module. I have declared and exported the ...

The Angular application shell build has produced two new folders within the dist directory. I'm curious about their purpose and how they can

Whenever I execute the ng run my-app:app-shell -c production command, it creates 2 folders within the dist directory - one for the browser and one for the server. Now, I find myself with 2 different commands to use: npm build --prod (for a regular build) ...

Is it possible for TypeScript to automatically detect when an argument has been validated?

Currently, I am still in the process of learning Typescript and Javascript so please bear with me if I overlook something. The issue at hand is as follows: When calling this.defined(email), VSCode does not recognize that an error may occur if 'email ...

Angular 2 Directive for Ensuring Required Conditions

Is there a way to make form fields required or not based on the value of other fields? The standard RequiredValidator directive doesn't seem to support this, so I've created my own directive: @Directive({ selector: '[myRequired][ngControl ...

Angular tips: Retrieving user ID for API authorization

Within the authorize.service.ts file, there is a service code block that allows me to retrieve the current logged in user's userName: public getUser(): Observable<IUser | null> { return concat( this.userSubject.pipe(take(1), filter( ...

I'm unsure how to utilize the generic type in this particular scenario. It's a bit confusing to me

Recently, I delved into TypeScript generics and applied them in specific scenarios. However, I encountered some challenges. While working with two different interfaces, I faced a need for flexibility. For instance, I needed to make server requests. func ...

Mastering the art of implementing md-table with services in Angular 4

I am a newcomer to the world of angular and I am attempting to utilize the new md-table component in Angular Material 2 with Angular 4. I have created a service that fetches simple arrays of content from an API. However, I am struggling to use this servic ...

Observable in RXJS, with a pipe that transforms based on a dynamic function

I want to create an observable that gets populated with a custom pipe every time it is called. Let me explain this concept with an example: const myObservable = timer(1000); return myObservable.pipe(getCustomPipe()); function getCustomPipe() { return c ...

Next.js routes handlers do not have defined methods parameters

Struggling to find the cause of undefined params Currently delving into the world of Nextjs api routes, I keep encountering an issue where my params are coming up as undefined when trying to use them in the HTTP method. My setup includes prisma as my ORM ...

Error: Attempting to access the 'presence' property of an undefined value

Having trouble with calling loading/Toast/Alert in Ionic2 under the current scenario. Being a newcomer to Ionic development, I'm struggling to understand it. I realize it's a trivial mistake. var dg = document.getElementById('btnregis&apos ...

Dynamic Mat-select-trigger that automatically adjusts its size to fit the content

Currently, I am experimenting with an Angular Mat-Select that allows multiple selections. To display the selected values in the value field, I have implemented a custom Mat-Select-Trigger. My goal is to enable automatic resizing of the value field (similar ...

You cannot assign an array of 'Contact' objects to a single 'Contact' parameter

During the development process, I encountered an error while trying to add a new contact. The error message states: Error: src/app/contacts/contacts.component.ts:32:28 - error TS2345: Argument of type 'Contact[]' is not assignable to parameter o ...

Imported modules are not being blocked by APP_INITIALIZER

In my Angular application (version 6.0.0), I am working on setting up runtime configuration using APP_INITIALIZER to pull in the configurations. While consulting various articles and Stack Overflow questions, such as this one and that one, I have managed t ...

Adjust the starting color of a mat-input in Angular 9

I am encountering an issue with the styling of a standard matInput field within a mat-form-field, all contained within a [formGroup] div. The dark background of the parent element is causing visibility problems with the default dark text color of the input ...

Issue: The login.component.html file failed to load

I attempted to utilize a custom-made HTML file with the templateUrl attribute in Angular2. Below is the content of my login.component.ts file: import {Component} from '@angular/core'; @Component({ selector: 'login' , template ...

Safari encountering parsing date error

My Angular application is receiving date formats from a web service in the following format: myDate = "2020-03-05T08:00:00" This translates to the fifth of March, 2020 for me For Chrome, Firefox, and IE, the format is yyyy-mm-ddThh:mm:ss However, Safar ...

Can someone please explain how to display a specific element from a JSON Array?

Is there a way to display only this specific part? /db/User_DataDb/61500546-4e63-42fd-9d54-b92d0f7b9be1 from the entirety of this Object obj.sel_an: [ { "__zone_symbol__state":true, "__zone_symbol__value":"/db/User_DataDb/61500546-4 ...

Can you explain the distinction between Observable<ObservedValueOf<Type>> versus Observable<Type> in TypeScript?

While working on an Angular 2+ project in Typescript, I've noticed that my IDE is warning me about the return type of a function being either Observable<ObservedValueOf<Type>> or Observable<Type>. I tried looking up information abou ...

What is the best way to spy on child components within an Angular application?

The Angular tutorials feature an example of a HeroesComponent with a child component named HeroesListComponent. Within the HeroesListComponent, there is a usage of the HeroesService to execute the getHeroes() function. In order to utilize the spyOn funct ...