Interactive loadChild components

I've been attempting to dynamically import routes from a configuration file using the following code snippet:

export function buildRoutes(options: any, router: Router, roles: string[]): Routes {
    const lazyRoutes: Routes = Object.keys(options)
        .map((key) => {
            const entry: RouteConf = options[key];
            const auth = entry.authRoute as string[];
            let output: Route =   {
                path: entry.routePath,
                redirectTo: 'fallback',
            };
            if (auth.some(item => roles.includes(item))){
                console.log(entry.exposedModule,entry.ngModuleName);
                output = {
                    path: entry.routePath,
                    loadChildren: () => import(entry.exposedModule).then((m) => m[entry.ngModuleName])
                }
             }
            return output;
        });

    return [...lazyRoutes,...APP_ROUTES ];
}

however, I'm encountering the following error:

ERROR Error: Uncaught (in promise): Error: Cannot find module '../richieste/richieste.module'
Error: Cannot find module '../richieste/richieste.module'

if I manually set the same data in the loadChildren, like this:

....
loadChildren: () => import( '../richieste/richieste.module').then((m) => m["RichiesteModule"])
....

everything works fine.

Is there a way to dynamically import modules for LazyLoading?

Thanks

Answer №1

A solution to the problem can be found by utilizing dynamic imports for Lazy Loading within your code. When employing dynamic imports, it is important to keep in mind that module paths are resolved relative to the location of the file containing the import statement. In this particular scenario, the value stored in entry.exposedModule contains a relative path ('../richieste/richieste.module'), which leads to an error due to the inability to locate the module.

To resolve this issue, you can utilize the import.meta.url property, which supplies the URL of the current module. Through combining import.meta.url with the new URL() function, it becomes possible to generate an absolute path to the desired module.

The following adjustment addresses the problematic loadChildren line:

loadChildren: () => import(new URL(entry.exposedModule, import.meta.url).toString()).then((m) => m[entry.ngModuleName])

By making use of

new URL(entry.exposedModule, import.meta.url)
, an absolute URL to the module is crafted based on the current module's URL and the specified relative path in entry.exposedModule.

This modification ensures that the module path is resolved accurately, enabling the dynamic importation of modules within the Lazy Loading setup. I hope this proves beneficial for your needs ;)

Answer №2

When you include a module using the syntax

import( '../requests/requests.module')
, it will be automatically compiled by your scaffolding tool (whether webpack or another).

However, if you dynamically import a module using import(entry.exposedModule), it will not be compiled automatically. You'll need to compile it independently and provide a URL for loading.

You can create a map that lists all the necessary modules or utilize module federation, which is an efficient approach to achieve this.

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 Angular Sortable Containment feature ensures that items cannot be dropped outside of

I am experiencing an issue with a horizontal sortable Angular list where the containment option is not functioning properly, causing the dragged item to not be dropped. Take a look at the sortable list below without a containment option - you may notice t ...

What is the best approach to perform type checking on a function that yields varying types depending on the values of its

Currently, I am facing a challenge with a function that takes an argument and returns a different type of value depending on the argument's value. For instance: function foo(arg: 'a' | 'b') { if (arg === 'a') { ret ...

The type 'number[]' is lacking the properties 0, 1, 2, and 3 found in the type '[number, number, number, number]'

type spacing = [number, number, number, number] interface ISpacingProps { defaultValue?: spacing className?: string disabled?: boolean min?: number max?: number onChange?: (value: number | string) => void } interface IFieldState { value: ...

The type 'Observable<boolean>' cannot be assigned to type 'Observable<UserRegistration>'

function completeRegistration(email: string, password: string, firstName: string, lastName: string, location: string): Observable<UserDetails> { let body = JSON.stringify({ email, password, firstName, lastName,location }); let headers = new H ...

Obtain the HTML result from a JavaScript Angular template

How can I access the processed HTML of an angular template within a JavaScript function without using directive overhead? Imagine if the template was located at "/scheduler/tooltip.html" and contained something like: <div>{{tip.Name}}</div ...

Using optional function arguments with destructured arguments in TypeScript can result in throwing an error

interface Type1 { attr1: string; attr2: string; } interface Type2 { attr1: string; attr2: string; attr3: string; // additional attribute } function fn(config: Type1 | Type2): void { // The error code is displayed above. I am ...

The options passed to createReadStream in TypeScript do not accept {start: 90, end: 99}

After updating to TypeScript 1.6.2, I encountered an issue with my call to createReadStream(). The problem arises because the type definition in node.d.ts does not recognize 'start' and 'end' in the options parameter. var st = fs.crea ...

What steps can I take to prevent Internet Explorer from caching my webpage?

After implementing Spring MVC for Angular JS on the front end, I encountered an issue where logging in with different user credentials resulted in incorrect details being displayed. This problem only occurred in Internet Explorer, requiring me to manually ...

Testing a service resolution in a controller through unit testing

As I attempt to create a test for my home module, I keep encountering an error that reads "unknown provider: service." Interestingly, when I modify resolveSomething in my home module to output a string, the app functions as expected, indicating that the re ...

The ng-click directive does not function properly when used in conjunction with dynamic HTML

My issue involves creating dynamic html in HTML where ng-click is not functioning properly. Here is my code snippet: window.imagePicker.getPictures( function(results) { for (var i = 0; i < results.length; i++) { console.log(&apo ...

An error occurred while trying to set the property 'IS_CHECK' of an object that is undefined

I'm attempting to create a checkbox that, when selected, should also select everything else. I followed the code example provided in this tutorial for angular 2. However, I encountered an error: "ERROR TypeError: Cannot set property 'IS_CHECK&ap ...

RxJS: the art of triggering and handling errors

This is more of a syntax question rather than a bug I'm facing. The process is straightforward: Send an HTTP request that returns a boolean value If the boolean is true, proceed If the boolean is false, log a warning and stop the flow. To handle ...

Why does `react/require-default-props` still display an error even when a default prop value has been set?

This inquiry pertains to the guideline require-default-props. Here is the code snippet in question: function MyComponent({ blubb = 'my default', }: { blubb?: string, }) { // blubb defaults to 'my default' }; Eslint is flagging a ...

Incorporating yarn into your Vue3 project with Typescript

I'm attempting to implement a solution from https://yarnpkg.com/package/vue-disable-autocomplete that disables autocomplete in my Vue3 project. After running yarn add vue-disable-autocomplete, I included the following code: import DisableAutocomplete ...

Ensuring type safety for functions with multiple definitions in TypeScript

The code provided above is prone to failure. TypeScript may mistakenly infer the return type as `string`, allowing you to use the `charAt` method on it even though the actual type is `number`. Is there a solution to enhance the code in a way that TypeScri ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

What methods are available to restrict the values of properties to specific keys within the current type?

I am looking to declare an interface in typescript that is extensible through an indexer, allowing for the dynamic association of additional functions. However, I also want sub properties within this interface that can refer back to those indexed functio ...

Discover the process of dynamically importing JavaScript libraries, modules, and non-component elements within a Next.js

Lately, I have been utilizing Next.js and mastering its dynamic import feature for importing components with named exports. However, I recently encountered a particular npm package that functions only on the client-side (requires window) and has a substant ...

Execute the npm run build command to build the Angular app using Gradle task

I am working on an Angular 1 application. After running npm run build I also need to initiate a Gradle task. Is there a way to automate this process? ...

Solving the issue of loading Ember Initializers during the transition to TypeScript

While following the ember quick start tutorial, I attempted to switch from Javascript to Typescript. Converting the .js files to .ts files resulted in an error with the ember-load-initializers import. The application is unable to run until this issue is re ...