Fixing the "Module not found" error in an Angular library using npm link

I'm currently working on creating an Angular wrapper for a Javascript library, but I've encountered a "Module not found" error. The Javascript library is still in development and has not been published to NPM yet. To work around this issue, I have opted to use npm-link, although this might be the source of the problem. My current Angular version is 8.2.2.

Javascript Source Library

sourcelib/index.js:

var sourcelib = (function () {
    var doSomething = function() {
    };
    return {
        doSomething: doSomething
    };
})();
export default sourcelib;

The sourcelib directory includes files such as package.json and README.md. To create an npm-link, I used the following commands:

cd sourcelib
npm link

Angular Wrapper

Below are the steps I followed using Angular CLI to set up the Angular workspace, library, and test application:

ng new app-test --create-application=false
cd app-test
ng generate library testlib
ng generate application testlib-app

To link testlib with the Javascript library, I did the following:

cd projects/testlib
npm link sourcelib

I then proceeded to generate a module and component within testlib:

cd src/lib
ng generate module test
ng generate component test/testcomp

testcomp.component.ts:

import { Component, OnInit } from '@angular/core';
import sourcelib from 'sourcelib';

@Component({
    selector: 'testcomp',
    template: '<div></div>'
})
export class TestcompComponent implements OnInit {
    constructor() { }

    ngOnInit() {
        sourcelib.doSomething();
    }
}

public-api.ts:

export * from './lib/test/test.module';
export * from './lib/test/testcomp/testcomp.component';

Next, I built the sourcelib:

ng build

This led to the following console output:

Building Angular Package

------------------------------------------------------------------------------
Building entry point 'testlib'
------------------------------------------------------------------------------
Compiling TypeScript sources through ngc
Bundling to FESM2015
Bundling to FESM5
Bundling to UMD
WARNING: No name was provided for external module 'sourcelib' in output.globals – guessing 'sourcelib'
Minifying UMD bundle
Copying declaration files
Writing package metadata
Built testlib

------------------------------------------------------------------------------
Built Angular Package!
 - from: /Users/.../app-test/projects/testlib
 - to:   /Users/.../app-test/dist/testlib
------------------------------------------------------------------------------

Afterwards, I created an npm-link to sourcelib:

cd ../../dist/testlib
npm link

Angular Test App

I linked testlib-app with testlib by running the command below:

cd ../../projects/testlib-app
npm link testlib

app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { TestcompComponent } from 'testlib';

@NgModule({
    declarations: [
        AppComponent, TestcompComponent
    ],
    imports: [
        BrowserModule
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts:

import { Component } from '@angular/core';
import { TestcompComponent } from 'testlib';

@Component({
    selector: 'app-root',
    template: '<testcomp></testcomp>'
})
export class AppComponent {
}

To serve the app, I initiated the command:

ng serve

Result

ERROR in /Users/.../app-test/dist/testlib/fesm2015/testlib.js
Module not found: Error: Can't resolve 'sourcelib' in '/Users/.../app-test/dist/testlib/fesm2015'
ℹ 「wdm」: Failed to compile.

I have tried troubleshooting this issue extensively but haven't had any luck finding a solution. Any assistance would be greatly appreciated.

Answer №1

When using Angular, you may encounter difficulties when building with linked modules. One possible solution is to include "preserveSymlinks": true in your angular.json file within the

projects.yourProject.architect.build.options
section. Take a look at this example:

{
  "projects": {
    "yourProject": {
      "architect": {
        "build": {
          "options": {
            "preserveSymlinks": true
          }
        }
      }
    }
  }    
}

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 initial value in useEffect is not being updated by useState

I am currently implementing a like feature for my web application. The issue lies in the fact that my setLike function is not updating the state even after using setLike(!like). I verified this by adding console.log() statements before and after the setLik ...

Guide to waiting for an event to finish in Angular

My component features a scorebar positioned on the left side, with game logic being managed by a separate game service. When a new player joins, I need to temporarily hide the scorebar, update the players array in the game.service, and then display the sco ...

The state in Reactjs is not displaying as expected

Check out my ReactJS todo app that I created. However, I am facing an issue with deleting todos. Currently, it always deletes the last todo item instead of the one I click on. For example, when trying to remove 'Buy socks', it actually deletes ...

Facing a problem with running npm start on jHipster

I am currently working on a jhipster project on my MacBook Pro running macOS Mojave v.10.14.4. After successfully compiling with npm start, the code continues to compile multiple times without any changes. Eventually, it throws the following error: DONE ...

Design the parent element according to the child elements

I'm currently working on a timeline project and I am facing an issue with combining different border styles for specific event times. The main challenge is to have a solid border for most of the timeline events, except for a few instances that share a ...

Utilizing Regular Expressions in AngularJS to validate name, a 10-digit mobile number, and a 12-digit number through the ng-blur event and match

I am struggling to validate the three inputs mentioned above and having trouble using the right functions. Can someone please assist me with this? Here is the HTML code for the 3 inputs: <input id="name" ng-model="user.name" ng-blur="checkIfNameIsVali ...

Utilizing the power of generics alongside index type manipulation

After successfully running this code: const f = <T extends string>(x: T) => x; f(""); interface Dictionary<T> { [key: string]: T; } const dict: Dictionary<number> = { a: 1 }; I anticipated the following code to work as well: interf ...

AngularJS: Calculate the total sum of array elements for generating charts

When using tc-angular-chartjs, I have successfully implemented a pie chart but am struggling to sum the label values for proper display. Additionally, while I can create a bar chart using their example, I encounter issues when trying to use external data f ...

Struggling with sending a post request in Node.js as the response always returns with an empty body

Here is the structure of my project And this error pops up when I run my program using npm run dev command I'm working on a basic webpage where users can input their name, email, and job details. I then try to insert this information from the HTML fo ...

Issue with Refreshing onRowAdd in React Material Table

I am currently using Material Table to display my table data. However, when I use the onRowAdd function to add a new row, the page does not refresh properly. Instead, it reloads and gets stuck, requiring me to manually refresh again. newData => ...

How to enhance and expand Material-UI components

I am trying to enhance the Tab component using ES6 class in this way: import React from "react"; import {Tab} from "material-ui"; class CustomTab extends Tab { constructor(props){ super(props); } render(){ return super.rende ...

What steps can be taken to ensure express Node.JS replies to a request efficiently during periods of high workload

I am currently developing a Node.js web processor that takes approximately 1 minute to process. I make a POST request to my server and then retrieve the status using a GET request. Here is a simplified version of my code: // Setting up Express const app = ...

Is it possible to trigger a textbox text change event after autocompleting using jQuery

I recently implemented a jquery autocomplete plugin for a textbox: $('#TargetArea').autocomplete({ source: '@Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })' }); The implementation is working as expected. ...

Streamline imports with Typescript

Is there a way to import modules with an alias? For example, I have an angular service in the folder common/services/logger/logger.ts. How can I make the import look like import {Logger} from "services" where "services" contains all my services? I've ...

Encountering a TS2739 error while retrieving data in an Angular service function

In my code, I have created a function to fetch objects from my dummy data and assign them to a variable. setData(key: string) { let dataChunk: ProductIndex = PRODUCTDATA.filter(a => {a.productId == key;}); this.ProductData = dataChunk; } The i ...

What can be done to fix the npm ERR! missing issue?

Recently, I upgraded to a new version of Windows OS on my PC and lost all my settings. I have also installed node and two global npm packages on my system. However, when I run the command npm list -g --depth=0 or npm list -g, I encounter multiple errors. I ...

Creating a layered image by drawing a shape over a photo in Ionic using canvas

While there are plenty of examples demonstrating how to draw on a canvas, my specific problem involves loading a photo into memory, adding a shape to exact coordinates over the photo, and then drawing/scaling the photo onto a canvas. I'm unsure of whe ...

Setting character limits within textareas based on CSS classes in a dynamic manner

I'm looking to develop a JavaScript function that can set text limits for multiple textareas at once using a class, allowing for flexibility in case specific textareas need to be exempt. However, I'm facing issues with my debuggers - Visual Studi ...

Choosing dynamically created components:Making a choice among elements that are generated

Currently, I am working on a task that involves moving list items between two separate lists and then returning them back upon a click event trigger. Below is a snippet of the basic HTML structure: Unchosen: <br> <ul id="unchosen"></ul> ...

I am having trouble getting the jsTree ajax demo to load

I am having trouble running the basic demo "ajax demo" below, as the file does not load and the loading icon continues to churn. // ajax demo $('#ajax').jstree({ 'core' : { 'data' : { ...