Initial compilation of Angular 2 project with lazy-loaded submodules fails to resolve submodules

I'm working on an Angular 2 project (angular cli 1.3.2) that is structured with multiple modules and lazy loading. In my main module, I have the following code to load sub-modules within my router:

{
    path: 'module2',
    loadChildren: 'modules/module2/module2.module.ts#Module2Module',
    canActivate: [Guard]
},

However, when I run ng serve, I encounter the following error message:

ERROR in Could not resolve "modules/module2/module2.module.ts" from "<..>/app/app.module.ts".

Oddly enough, whenever I save any file in the project (triggering a re-build), the build is successful and both modules function correctly without needing to actually make any changes. Has anyone experienced this issue before or know of a way to resolve it?

Any help would be greatly appreciated.

Answer №1

If you're looking to optimize your website's loading time, implementing lazy-loading could be a beneficial solution.

To configure lazy-loading in your Angular application, make sure to include the necessary entry in your app-routing.module.ts file. Here is an example of how it should look:

{
    path: 'module2',
    loadChildren: './modules/module2/module2.module#Module2Module',
    canActivate: [AuthGuard]
}

It's important to note that there should not be a file extension included in the module's path for lazy-loading to work efficiently.

Answer №2

After troubleshooting, I found a solution by removing Lazy Loading:

To fix the issue, make sure to include both imports in the app.module.ts file for app.router.ts and

modules/module2/module2.module.ts
. Also, ensure that Module2 is placed before the main App router within the '@NgModule' 'includes' section:

import { RouterModule, Router } from '@angular/router';
import { NgModule } from '@angular/core';

import { appRoutes } from './app.router';
import { Module2 } from './modules/module2/module2.module';

// Other imports

@NgModule({
  declarations: [..],
  imports: [
    ..,
    Module2,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [..],
  entryComponents: [..],
  bootstrap: [..]
})
export class AppModule {  }

The error experienced was caused by the incorrect order of imports, as outlined in Milestone 3 of the Angular Routing Guide

I appreciate the helpful suggestions provided by fellow contributors!

Answer №3

It seems like there may be a better solution to your issue. While your app is currently compiling, the lack of lazy loading could lead to slow initial load times as your app grows in size.

Lazy loading allows modules to be loaded separately through individual JavaScript requests rather than being compiled into one large file. This customizable feature can greatly improve performance for larger production apps, allowing modules to be loaded either aggressively or as the user navigates through the site.

Based on suggestions from @AndreaM16, it appears that there might be an error in your routing configuration, specifically with the naming convention for "Module2". It should be referenced simply as "Module2" instead of "Module2Module". You can try adjusting the code snippet below:

{
    path: 'module2',
    loadChildren: './modules/module2/module2.module#Module2Module',
    canActivate: [Guard]
},

If this adjustment does not resolve the issue, providing insight into your file structure and possibly sharing the Module2 code could be beneficial.

Additionally, remember to remove references to Module2 in your AppModule, including the import statement { Module2 } from './modules/module2/module2.module'. By using a magic string for lazy loading, webpack will not bundle the module code into the initial JavaScript package, ensuring it is loaded only when needed.

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

Adding the expiry date/time to the verification email sent by AWS Cognito

After some investigation, I discovered that when a user creates an account on my website using AWS Cognito, the verification code remains valid for 24 hours. Utilizing the AWS CDK to deploy my stacks in the AWS environment, I encountered a challenge within ...

Importing dynamically into Ionic 2 from locations other than the "node_modules" directory

I've recently reviewed the documentation for ModuleResolution in TypeScript on this page: https://www.typescriptlang.org/docs/handbook/module-resolution.html#node My understanding is that all files I wish to import must reside within the node_modules ...

Using multiple instances of ngrx stores within a single application

Can one create a unique instance store for each component instance, similar to services declared in the providers array of the component decorator? ...

Creating a customized Axios instance in Typescript can provide more flexibility and control over

I am looking to create an API with a customizable instance using Axios. Ideally, I want to be able to use a basic instance like this: api.get("url")... In addition, I would like to have the flexibility to add dynamic bodies and access them using something ...

Angular is a powerful framework that enables the creation of dynamic user interfaces. One of its many

Looking to implement a Material table with expandable rows in Angular. table-tree.html <table mat-table [dataSource]="dataSource" multiTemplateDataRows class="mat-elevation-z8" > <ng-container matColumnDef="{{co ...

Transforming Boolean data types into text within an Angular 2 client-side application

Query I'm currently working on retrieving data from an API and displaying it in a table. One of the columns includes a status attribute that returns either true or false values. However, I would like to display "Active" or "Block" instead on the clie ...

error TS2304: The term 'MediaRecorder' is not recognized

How can I add audio recording capability to my Angular application using media recorder? Unfortunately, I am encountering the following error: Error TS2304: 'MediaRecorder' cannot be found If anyone knows a solution for this issue, your help w ...

Use ngClass to dynamically change the color of a button when it is clicked. This functionality can be applied to buttons

In my application, there are 80 buttons displayed on the screen using the following code: <tr *ngFor="let plans of PlanList"> <td class="text-primary">{{plans.typename}} </td> <td class="text-center&quo ...

Identify when a browser tab is closed and determine which specific tab out of all the open tabs was closed

Is there a way to identify when a browser or tab is closed in Angular/JavaScript? I would like to know if there are specific events that can be used for detecting these actions. Any advice, information, or code examples on this topic would be greatly app ...

Overriding a generic property in Typescript allows for a more

I'm troubleshooting an issue with my code: class Base<T> {} class Test { prop: Base<any>; createProp<T>() { this.prop = new Base<T>(); } } const test = new Test(); test.createProp<{ a: number }>(); test.pr ...

Guide to implementing a specified directive value across various tags in Angular Material

As I delve into learning Angular and Material, I have come across a challenge in my project. I noticed that I need to create forms with a consistent appearance. Take for example the registration form's template snippet below: <mat-card> <h2 ...

Is it possible to transmit fixed routing information utilizing a path that can be customized with parameters?

Within my route definition, I am passing static data like this: const routes: Routes = [{ path: '/map', component: MapComponent, data: { animation: 'mapPage' } }]; To access this data ...

Encountering issues with the command npm install --save web-animations-js, the

Issue encountered while trying to run "npm install --save web-animations-js". It seems like the request to https://registry.npmjs.org/web-animations-js failed due to a mismatch in the Hostname/IP in the certificate. The error message indicates that the Hos ...

What is the best approach to implementing a blur function for a specific input within a parent component?

I have created a custom input field as a separate component. I want to include multiple input fields in the parent component using directives: <app-input ...></app-input> My goal is to pass the blur event/function to the parent component speci ...

Is it necessary for Vue single file components (.vue files) to use `export default` or is it possible to use named exports instead?

export default may no longer be the recommended way to export modules, as discussed in these resources: After changing my Vue components from this: <script lang="ts"> 'use strict'; import {store} from '../../data/store' ...

Angular 6 Calendar Template issues with parsing: Unable to link to 'view' as it is not recognized as a valid property of 'div'

I am in the process of developing an application that utilizes this angular calendar. My tech stack includes Angular 6 with AngularFire2 and Firebase. Below is my app.module.ts file: import { BrowserModule } from '@angular/platform-browser'; imp ...

What is the best way to bring in this interface from the React-Particles-JS library?

I have been attempting to segregate my parameters from my JSX within the react-particles-js library. I organize my parameters in an Object: let config = { "particles": { "number": { "value": 50 }, ...

Adjusting the quantity of items in the blueprintjs Suggest component

In my current project, I have developed a react app using the blueprintjs visual toolkit. However, I am facing an issue where the <Suggest> box is displaying all elements from the array, instead of just the first 10 as shown in the documentation. Bel ...

Creating a Custom Select Option Component with Ant Design Library

Is it possible to customize options in an antd select component? I have been trying to render checkboxes alongside each option, but I am only seeing the default options. Below are my 'CustomSelect' and 'CustomOption' components: // Cu ...

Restricting the number of mat-chips in Angular and preventing the input from being disabled

Here is my recreation of a small portion of my project on StackBlitz. I am encountering 4 issues in this snippet: I aim to restrict the user to only one mat-chip. I attempted using [disabled]="selectedOption >=1", but I do not want to disable ...