Having trouble importing components from the module generated by Angular CLI library

After creating a simple Angular library using CLI with the command

ng g library <library-name>
, I encountered an issue while trying to import a component from its module. In my app module, I added components.module to the imports array and attempted to import a components class to another component like this:

import {MyComponent} from ...;

However, my IDE indicated that the Module did not have any exported members with the name of my component. When I checked the module file, it looked like this:

export declare class ComponentsModule {
}

The public_api.d.ts file showed:

export * from './lib/components.service';
export * from './lib/components.component';
export * from './lib/components.module';

Furthermore, in the library-name.d.ts file:

/**
* Generated bundle index. Do not edit.
*/
export * from './public_api';
export { ApiErrorComponent as ɵa } from './lib/modals/api-error/api-error.component';
export { ConfirmationModalComponent as ɵb } from './lib/modals/confirmation-modal/confirmation-modal.component';
export { InfoModalComponent as ɵc } from './lib/modals/info-modal/info-modal.component';

Prior to running ng build, my module source file included:

import {NgModule} from '@angular/core';
import {ComponentsComponent} from './components.component';
import {ApiErrorComponent} from './modals/api-error/api-error.component';
import {ConfirmationModalComponent} from './modals/confirmation-modal/confirmation-modal.component';
import {InfoModalComponent} from './modals/info-modal/info-modal.component';

@NgModule({
  imports: [],
  declarations: [
    ComponentsComponent,
    ApiErrorComponent,
    ConfirmationModalComponent,
    InfoModalComponent,
  ],
  exports: [
    ComponentsComponent,
    ApiErrorComponent,
    ConfirmationModalComponent,
    InfoModalComponent,
  ],
})
export class ComponentsModule {
}

I'm confused about why I can't import these components even after generating the library using Angular CLI. The package contains directories such as ems2015, esm5, fesm5, fesm2015, and bundles beside "lib", but I expected to be able to easily import my module and use its components anywhere I wanted. It seems like they are private or inaccessible, and the documentation on generating and building libraries using CLI is lacking. Any help would be greatly appreciated.

Answer №1

Hopefully, you will come up with a solution before then. I faced the same issue and would like to share how I resolved it.

To address this problem, make sure to update your public_api.d.ts file in your library to include all of your custom components. Specifically, it should look something like this:

export * from './lib/modals/api-error/api-error.component';
export * from './lib/modals/confirmation-modal/confirmation-modal.component';
export * from './lib/modals/info-modal/info-modal.component';

After making these modifications, execute ng build <library-name>. Once your library-name.d.ts is set up this way, all of your components will be exported.

export * from './public_api';

When importing these components into another module, follow this pattern:

import {NgModule} from '@angular/core';
import {ComponentsComponent} from './components.component';
import {ApiErrorComponent} from 'library-name';
import {ConfirmationModalComponent} from 'library-name';
import {InfoModalComponent} from 'library-name';

Answer №2

After following a helpful guide, I created my own library and tested adding it to my local npm registry (Verdaccio). The guide I used can be found at this link.

However, when I attempted to import the library's module into my app, I encountered an issue where it couldn't be found, despite seeing the folder in my node_modules. It turned out that I had missed a crucial step during the publishing process after running ng build - I forgot to navigate to the library project's dist/my-library-name folder before publishing. Once I rectified this mistake and published the library from the correct location, I was successfully able to import the module into my app.

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

Encountering 'no overload matches this call' while developing a useReducer using React with Typescript

import { useCallback, useReducer } from "react"; const ARTIST_REDUCER_TYPES = { ADD: "ADD", }; const artistArray = [...Object.values(ARTIST_REDUCER_TYPES)] as const; type ActionReturnedTypes = (typeof artistArray)[number]; type Re ...

Tips for improving DOMContentLoaded performance with Angular2

Currently, I am in the process of converting a JQuery template to Angular 2, specifically a Dashboard-like template. This website has numerous popups, each containing multiple tabs, so I decided to separate each popup into different components to keep the ...

Ensuring all functions have finished executing and sending a response in Node.js - best practices

Below is the code snippet: route.get('/',function(req, res){ for(var e = 0; e < contactEmailArray.length; e++){ var currentContact = contactEmailArray[e]; setSentEmailCount(gmail, currentContact); setReceivedEmailCou ...

Unable to retrieve data header in the Angular 10 build version

I have a code snippet for an HTTP request: return this.http.post<any>(this.path.userRoot + '/logIn/random', body, { withCredentials: true, responseType: "json", observe: 'respon ...

What is the process for defining a series of tests for karma through code?

Currently, I am in the process of developing an Angular Test Explorer. The exciting part is that I can view all the tests and execute them collectively by leveraging the karma module as shown in this code snippet: public async runWithModule(): Promise&l ...

What is the correct way to handle the return value of an useAsyncData function in Nuxt 3?

How can I display the retrieved 'data' from a useAsyncData function that fetches information from a pinia store? <script setup lang="ts"> import { useSale } from "~/stores/sale"; const saleStore = useSale(); const { da ...

When attempting to compile Typescript code, error TS1128 occurs indicating a missing declaration or statement. However, the code functions correctly when executed through a server

Currently, I'm in the process of developing a project using Angular2. As part of this project, I have created a primary Component class which serves as a central piece: import { Component, OnInit} from '@angular/core'; import { submitServi ...

WebStorm lacks support for TypeScript's `enum` and `readonly` features

When working with TypeScript in WebStorm, I encountered an issue where the IDE does not recognize enum or readonly. To solve this problem, I delved into TypeScript configuration files. I am currently utilizing .eslintignore, .eslintrc, tsconfig.json, and ...

Patience is key as you await the completion of an API call in Angular 14

Within my Angular 14 application, I am faced with a scenario where I need to make two API calls and then combine the results using "combineLatest" from rxjs. The combined data is then assigned to a variable that I must use in a separate function. How can I ...

What is the reason for Akita statestore returning an empty entity instead of the updated entity?

I'm utilizing Akita as the state management solution for my Angular application. Currently, I can retrieve data from a backend server and populate my store successfully (the data is displayed in components). However, when attempting to update an enti ...

In the Chrome task manager, an Angular 6 website is initially seen with a memory footprint of 1.3 GB, which then decreases to just 160 MB after a

While utilizing Angular 6, our website experiences a significant spike in memory footprint during loading, starting at 100MB and reaching 1.3GB before dropping back down to 160MB shortly after completion. https://i.sstatic.net/FhHB7.png https://i.sstatic. ...

Angular Reactive Forms provide a method to connect a data object with each element within a FormArray

Currently, I am in the process of constructing a reactive form that resembles the image depicted below - In the image, each file (referred to as an attachment in the code) contains multiple agendas. These agendas can be added, updated, and deleted. bui ...

What is the best way to combine data from two rows into one row?

Can someone help me with merging 2 sets of Line data into a single row for each entry? For example, the 'Green Bay Packers @ Chicago Bears' row should display '+3.5000 and -3.5000', while 'Atlanta @ Minnesota' should show &apo ...

Unable to export Interface in Typescript - the specific module does not offer an export named Settings

I am encountering an issue while trying to export/import an interface in Typescript. The error message I receive is causing confusion as I'm unsure of where I went wrong. Uncaught SyntaxError: The requested module '/src/types/settings.ts' ...

What is the process for type checking a Date in TypeScript?

The control flow based type analysis in TypeScript 3.4.5 does not seem to be satisfied by instanceof Date === true. Even after confirming that the value is a Date, TypeScript complains that the returned value is not a Date. async function testFunction(): ...

Exploring the depths of Angular2 RC6: Implementing nested modules and routing

Within my application, I have a module called SupportModule which consists of 3 sub-modules: AdminModule, ChatModule, and ContactModule. Each of these modules has its own defined routing structure. The overall structure resembles something like this: htt ...

What is the best way to retrieve environment variables from an NPM package in an Angular 5 application

Is there a method for my node module, created from an Angular 5 application, to access the environment variable from the Angular 5 application (environments/environment.ts)? Perhaps Angular 5 exports its environment variables to JavaScript global variables ...

VScode has identified potential problems with modules that utilize Angular Ivy, however, this should not cause any major issues

Encountering a problem with using Angular in VSCode, where there seems to be no ngModules due to AngularIvy. The error message indicates an issue with 'CommonModule' not being recognized as an NgModule class: [{ "resource": "[...]src/app/com ...

Ways to implement logging in an NPM package without the need for a specific logging library

Currently, I am in the process of developing a company npm package using TypeScript and transferring existing code to it. Within the existing code, there are instances of console.log, console.warn, and console.error statements, as shown below: try { c ...

The comet crash application is experiencing technical difficulties on Ubuntu version 14.01

jayesh@jayesh-VirtualBox:~/meteroapp/leadengine$ sudo npm install -g meteorite [sudo] password for jayesh: npm http GET https://registry.npmjs.org/meteorite npm http 304 https://registry.npmjs.org/meteorite npm http GET https://registry. ...