Discovering the cause of the "Module not found" error for nrwl packages

In my project, I have integrated nrwl.io.

I have set up multiple libraries:

ng g lib rest //successfully created
ng g lib services //successfully created
ng g lib models //created without errors, but encountering "Cannot find module" issue later on!

Even though all libraries were created successfully, when attempting to import the models library, I encounter the error "Cannot find module":

import { ModelA, ModelB } from '@myproj/models'; //Cannot find module '@myproj/models'

My question is: Where and how can I verify if my '@myproj/models' library was properly registered?

P.S. I have confirmed that the "models" module is included in nx.json, angular.json, and tsconfig.json. I do not see any discrepancies compared to other modules.

P.P.S. I am using "@nrwl/nx": "6.1.0" and "@nrwl/schematics": "6.1.0"

Answer №1

I once made the mistake of not restarting my TypeScript server in VS Code, simply because I overlooked it:

To fix this issue, you can try the following:
CMD / CTRL + SHIFT + P
>TypeScript: Restart TS Server

Answer №2

Having encountered the same challenge, I decided to create a library and utilize it across multiple projects. The first step is to ensure that your library is included in the main tsconfig.json file under the paths property.

"paths": {
  "@projectName/LibraryName1": ["libs/LibraryName1/src/index.ts"],
  "@projectName/LibraryName2": ["libs/LibraryName2/src/index.ts"],
  ....
}

Next, you need to add your project to the main angular.json file.

"projects": {
   "LibraryName1": {
   "root": "libs/LibraryName1",
   "sourceRoot": "libs/LibraryName1/src",
   "projectType": "library",
   "prefix": "projectName",
   "projectType": "library"
   ...
  }
}

Make sure to review the tsconfig.json file for the specific app where you intend to use the library. It's crucial to remove the paths property as it has already been added to the main tsconfig.json (in my case, I utilized nrwl for managing multiple apps).

Now, you should be able to reference any of your library projects like this:

import { class1, class2 } from '@projectName/libraryName1';

Don't forget to export your classes (assuming you have a models library) using the index.ts file:

export * from './lib/class1';
export * from './lib/class2';

If you have a UI library with components, create a module, add the components to it, and then export it using the index.ts file. The module file should be located in the lib folder. For example:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NumberOnlyDirective } from './directives/number-only.directive';

@NgModule({
imports: [CommonModule],
declarations: [NumberOnlyDirective],
exports: [NumberOnlyDirective]
})
export class UiModule {}

index.ts file for the UI library:

export * from './lib/ui.module';

Include the reference to the UI module in your project's app.module.ts file:

import { UiModule } from '@projectName/LibraryName1';

Ensure to include it in the imports section as well:

 imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
NgxPaginationModule,
Ng2OrderModule,
Ng2SearchPipeModule,
AngularEditorModule,
RichTextEditorAllModule,
NgxPrintModule,
DevExpressModule,
UiModule
...
],

Answer №3

I have also come across a similar issue.

Let's say we have a project called "project1" and a library called "library1" (which means we want to reference the module "@project1/library1"). When trying to reference NRWL NX generated library modules from non-Angular contexts (such as Ionic/Angular in my case), everything works smoothly. However, when working within Angular apps in the monorepo, it led to a "Cannot find module" error.

The root of the problem was that the Angular application was searching for the barrel file (index.ts) at the location "project1/libs/library1", while NX actually places the barrel file one level deeper at "project1/libs/library1/src".

In order to address this issue, the solution (though somewhat tedious) is to create an additional index.ts file at the "project1/libs/library1" location with the following content:

export * from './src';

By doing this, we ensure that the code functions correctly in all scenarios, and this solution only needs to be implemented once (for each new library generated) instead of having to manually add a reference to the package.json file of every Angular app in the repository.

Answer №4

If you're encountering this problem and the suggested solutions haven't worked for you, here's how I managed to solve it.

  • After some investigation, I discovered that I could import successfully in other areas, but the specific app I was working on was causing the problem.
  • This prompted me to inspect the tsconfig file for the app.
  • I realized that I had mistakenly set baseUrl: true in the tsconfig file, which was preventing the import from being resolved.

TLDR: Simply remove the baseUrl setting from the tsconfig file.

Answer №5

If you've integrated nx into an existing monorepo and encountered this error, here's the solution.

To resolve this issue, make sure to include the root tsconfig.base.json in your application's tsconfig.json file by adding the following code snippet:

{
...

 "extends": "../../tsconfig.base.json",

....
}

Answer №6

While working on a new library, I encountered a similar problem. I resolved it by deleting the node_modules directory and then reinstalling it. This simple step effectively solved the issue.

Answer №7

When utilizing @model/something for importing, the editor will conveniently include the complete module path (in my specific scenario). This led me to take the following steps in order to successfully utilize the import '@' feature.

  • Remove the automatically added full path import by the editor. Keep only the import you manually typed, such as @project/models.
  • Shutdown the server and restart ng serve.

Answer №8

When you're creating a library, the usage of

--parent-module=apps/myapp/src/app/app.module.ts
is crucial.

This flag plays a role in altering the tsconfig.app.json file and includes "../../libs/mylib/src/index.ts, instructing TypeScript to utilize the module.

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

What is preventing me from renaming a file in PHP when passed through jQuery?

Hello to all users! I've encountered an issue where I can't seem to change the file name in PHP that is being passed from jQuery: Here is the JavaScript code where I pass the file to the PHP handler: var url = '/temp.php'; var xhr = ...

Implementing Batch File Uploads using Typescript

Is there a way to upload multiple files in TypeScript without using React or Angular, but by utilizing an interface and getter and setter in a class? So far I have this for single file upload: <input name="myfile" type="file" multi ...

The Angular service uses httpClient to fetch CSV data and then passes the data to the component in JSON format

I'm currently working on an Angular project where I am building a service to fetch CSV data from an API server and convert it to JSON before passing it to the component. Although the JSON data is successfully logged in the console by the service, the ...

Update the content that corresponds to the regular expression in jQuery

I am on a quest to locate specific content that matches a regular expression across an entire webpage and then replace it with different text. Below is the code I have been utilizing for this task. var reg = /exam+ple/; $("body").html(function () { ...

Creating a smooth animated scroll to a specific #hash while keeping elements hidden on the page

I'm facing an issue with a JavaScript function that scrolls to a selected element with scroll animation. Everything is working fine, however, I encounter a problem when sliding up or down to show/hide certain elements. When a clicked link contains th ...

It appears that the Next.js environment variables are not defined

Upon setting up a fresh next.js project using npx create-next-app@latest and configuring some environment variables in the .env.local file, I encountered an error when attempting to run the server. "Failed to load env from .env.local TypeError: Cannot ...

How can you restrict the number of characters a user can input into an Angular input textbox?

I am using the textarea tag and I would like to limit the number of characters a user can type to 300. Currently, I have implemented real-time character count functionality, but I need to restrict input once it reaches 300 characters. Below is my HTML cod ...

Creating an uncomplicated search bar that dynamically adjusts values based on its function

Summing it up, there is a div situated within my app.component.html: <div class="col-lg-6 search-div"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search for..."> <span class="input-group-b ...

Transfer the html div element to the ajax request

My server-side code runs multiple bigquery queries and organizes the results in a table. The client calls this code via an ajax request. I want to send the table/div generated by the server-side code to the client so that it can be rendered there. Is this ...

Managing state with Apollo within a component

Greetings and thank you for taking the time to help me out. I am currently diving into the world of Apollo and React, but it seems like I am struggling with some logic here. On my main page index.js, I have initialized Apollo in the following way: export c ...

Can't seem to res.send using Express framework

Hello, I'm encountering an issue when trying to send a response using Express. I've seen suggestions in other questions that changing the variables err and res may resolve this problem, but it hasn't worked for me. router.post('/checkP ...

Utilizing Angular2 to access NPM package (Googleapis)

I am currently developing an Angular2 application that utilizes Webpack for the build process. I want to implement a Google oauth login feature in my application, so I have added the googleapi package from npm. However, I am facing difficulties when trying ...

The TypeScript compiler is tolerant when a subclass inherits a mixin abstract class without implementing all its getters

Update: In response to the feedback from @artur-grzesiak below, we have made changes to the playground to simplify it. We removed a poorly named interface method and now expect the compiler to throw an error for the unimplemented getInterface. However, the ...

Allow JavaScript to determine whether to link to an internal or external web address

Currently, I am in the process of setting up a new website and need to create an HTML page with some JavaScript that can determine whether to link to the external or internal IP address. I have researched some JavaScript code to fetch the IP address, whic ...

Keep an ear out for socket.io within an Angular application

I am trying to connect socket.io with my angular application. I have come across some examples of creating a service that can be accessed by the controller, and I understand that part. However, I am looking for a solution where all controllers can respond ...

A step-by-step guide on setting up an event listener for dynamically generated HTML using JavaScript objects

In my JavaScript code, I am creating object instances that include HTML elements in the form of buttons. These buttons are dynamic and have words generated dynamically as well. I want these buttons to execute certain functions when clicked. The challenge I ...

Is there a way to ensure that both new Date() and new Date("yyyy-mm-dd hh:mm:ss") are initialized with the same timezone?

When utilizing both constructors, I noticed that they generate with different timezones. Ideally, they should be in the same timezone to ensure accurate calculations between them. I attempted to manually parse today's date and time, but this feels li ...

Conditional generics in TypeScript based on a constructor argument

Within my class structure, I have the following: class Collection<ID extends string | number> { entries: ID[]; constructor(private readonly useStringIds: boolean) {} getIds(): ID[] { return entries.map((entry) => entry.id); ...

Modify Twig template variable using AJAX

I'm attempting to dynamically reload a section of my HTML with new data fetched through AJAX. Within the code, there is a loop that iterates over clients: {% for client in clients %} After making an AJAX request and receiving updated client informa ...

Using the Presentational - Container (or Smart - Dumb) component approach in conjunction with Vuex

When it comes to managing the Presentational - Container (or Smart - Dumb) component pattern with Vuex, what is your recommended approach? Should the Presentational (or Dumb) components emit events to the parent or call Vuex actions? Imagine a scenario w ...