Using Dynamic Imports in Angular 6 Libraries

After creating a sample Angular 6 Library using the Angular CLI, I have the basic structure with the library "my-lib" and the sample app "test-lib" for testing purposes.

Within the library, I am looking to implement dynamic imports. Specifically, I have a class that should be lazily imported:

export class Lazy {
    print(): void {
        console.log('I am lazy');
    }
}

Additionally, in my consumer component:

export class MyLibComponent implements OnInit {

  async ngOnInit() {
    const lazyImport = await import(/* webpackChunkName: 'lazy' */ './lazy');
    new lazyImport.Lazy().print();
  }
}

To support dynamic imports, I've compiled the library to the dist folder using "ng build my-lib" and changed the tsconfig module to esnext.

When trying to include the library in the sample app generated by the CLI, I noticed that the "lazy chunk" was not being generated when building or serving the app. This raised questions about the possibility of using dynamic loading within a library itself.

Switching the import path inside the app.module.ts from the compiled dist folder to the source code of the library resulted in the creation of the lazy chunk as expected. However, this approach is not ideal as it requires importing directly from the typescript sources.

Edit: Summary of my problem
Can a library self-trigger dynamic loading, or is this feature limited to the main app for lazy-loading other parts of the app or additional libraries?

Edit: Reason for the question
My library comprises numerous generated typescript classes, with only a few needed per use case. The goal is to load these on demand.

Thank you for your assistance!
Stephan

Answer №1

Everything is functioning flawlessly according to plan. All you have to do is compile the library, place it where necessary, and utilize the dynamic import method in your other project while referencing the built library with a relative path.

The Angular-CLI doesn't generate a chunk because it eliminates anything not referenced in the source code through tree shaking. If your import does not directly point to the lazy chunk, there is no reason for it to be built when executing ng build or ng serve on the application. However, running ng build my-lib will explicitly build 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

How to dynamically incorporate methods into a TypeScript class

I'm currently attempting to dynamically inject a method into an external class in TypeScript, but I'm encountering the following error. Error TS2339: Property 'modifyLogger' does not exist on type 'extclass'. Here's the ...

Is it advisable to specify data types for my JSON data in TypeScript?

For the shopping application in my project, I am utilizing a JSON structure to categorize products as either hot or branded. However, I encountered an issue when trying to define a type for the entire JSON object labeled "full". Despite my attempts, it app ...

Detecting the language of a browser

In my Angular2 application, I am looking to identify the browser language and use that information to send a request to the backend REST API with localization settings and variable IDs that require translation. Once the request is processed, I will receive ...

Explain the concept of a static async create method having identical parameters as the constructor

I have a lot of existing classes that require refactoring to utilize an async constructor. Here's an example: class ClassA { constructor(a: number, b: string, c: string) { //... } //... } I've included an async create method ...

What could be causing the excessive number of connections in my MongoDB instance?

This code snippet is crucial for my initial connection setup let cachedDbConnection: Db export async function establishDatabaseConnection(): Promise<{ db: Db }> { if (cachedDbConnection) { return { db: cachedDbConnection } } const client ...

Leverage the power of TypeScript with knockout's pureComputed function

I am facing an issue with referencing the this object in a function called problem: const c = { f() { console.log("hi"); }, problem: ko.pureComputed(() => { return this.f(); }), }; [ts] The containing arrow function captures the glob ...

Detecting Typescript linting issues in VSCode using Yarn version 3.2.3

Every time I try to set up a new react or next app using the latest yarn v3.2.3, my VS Code keeps showing linting errors as seen in the screenshot below. The main error it displays is ts(2307), which says Cannot find module 'next' or its correspo ...

Display a loading indicator in Angular during app initialization with APP_INITIALIZER

Is there a way to display a waiting indicator while the Angular app is running the app_initializer code? Currently, I can display a waiting indicator until the app is fully loaded. However, once the page loads, it remains empty until the app_initializer c ...

Replace Formik with useFormik to streamline your code

I have implemented Formik/Yup for validation on a page that triggers a GraphQL mutation. The code is functioning as expected: export default function RemoveUserPage() { const [isSubmitted, setIsSubmitted] = useState(false); const [isRemoved ,setIsRemo ...

Generating HTML content using Angular 8 and JSON data

Currently, I am managing an Angular Storybook that consists of various components. Within the stories.ts file of a component, there is a JSON snippet containing properties such as the content of a DIV element, shown below... { "accordionLink": ' ...

AngularDart's runtimeType object

My component is designed to accept a model object, but the type of this object determines which specific component will be rendered inside: <div [ngSwitch]="poolModel.runtimeType.toString()"> <template ngSwitchCase="CryptonoteMiningPool">& ...

Factory function in Angular for translating using arrow syntax

When I include TranslateModule using the following code: TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }) where export function HttpLoaderFactory(http: H ...

Using the async pipe on the MatTable datasource does not result in sorting functionality, but the table contents are updated correctly

I am encountering an issue with my MatTable that is not sorting when one of the headings are clicked, even though the arrow icon appears. The data loads and refreshes correctly when changes are made to the underlying data, but sorting seems to be a challen ...

Using React with Typescript involves using the React.createElement method

I am facing an issue with a reference to a FunctionalComponent in my object. When I try to pass this reference into the createElement statement, it triggers a TypeScript error. Question: Why is this error occurring? Both Component and FunctionalComponent ...

Troubleshooting CORS policy problems in an Ionic Angular application

I am attempting to run the following function in my Ionic Angular application, where cloudFunctionUrl represents a cloud function within my Firebase project: import { HttpClient } from '@angular/common/http'; private http: HttpClient like(post) ...

Tips for accurately documenting the Props parameter in a React component with Destructuring assignment

Attempting to create JSDocs for a React component using destructuring assignment to access props: const PostComponent: React.FC<IPostComponent> = ({ title, body }) => { ... } The issue arises when trying to document multiple parameters in JSDocs ...

Nextjs REACT integration for self-service registration through OKTA

Attempting to integrate the Okta SSR feature for user sign-up in my app has been challenging as I keep encountering this error message: {"errorCode":"E0000060","errorSummary":"Unsupported operation.","errorLink& ...

Apollo useQuery enables risky array destructuring of a tuple element containing any value

Currently, I am incorporating TypeScript into my project and have a GraphQL query definition that utilizes Apollo's useQuery. According to the documentation, the call should be typed, however, I am encountering an ESLint error regarding data being ass ...

Encountering an issue with Angular 13 routing where extraction of property fails when returning value as an observable

After receiving an id number from the parent component, I pass it to my child component in order to retrieve a value with multiple properties. To achieve this, I created a service that returns an observable containing the desired object. However, when atte ...

Using *ngFor with a condition in Angular 4 to assign different values to ngModel

I am new to Angular 4 and encountering an issue with using *ngFor in conjunction with HTML drop-down select and option elements. My categories array-object looks like this - categories = [ { id:1, title: 'c/c++'}, { id:2, title: 'JavaScri ...