Utilizing Lazy Loading Modules within an Angular 2 (v5) App

I'm struggling to implement lazy loading in my Angular 2 (version 5.1.3) project.

While following Todd Motto's guide on Lazy Loading Code Splitting, I am hitting a roadblock in getting it to function correctly.

My app consists of multiple modules, some of which I want to be lazily loaded as most users do not utilize the functionality and the app size is substantial with everything bundled together.

The route configuration in app.module looks like this:

export const routes: Routes = [
  { path: '', 
    redirectTo: 'login', 
    pathMatch: 'full'
   },
  { path: 'login', 
    component: LoginComponent
  },
  { path: 'home', 
    component: HomeComponent
  },
  { path: 'reports-engine', 
    loadChildren: './reportsengine/reportsengine.module#ReportsEngineModule'
  },
  { path: '**', 
    component: NotFoundComponent
  }
];

Here is the structure of the ReportsEngine module:

export const routes: Routes = [
  {
    path: '',
    component: ReportsComponent,
    children: [{ 
      path: '', 
          redirectTo: 'reports-engine',
          pathMatch: 'full'
        },
      { 
      path: 'account', 
          component: Account
        },
      { 
      path: 'accounts-manage', 
          component: AccountsManage
        },
      {
      path: '**', 
          component: NotFoundComponent
      }]
  }
];

In my webpack.config file (relevant parts), it is configured as follows:

output: {
    filename: '[name].js',
    chunkFilename: '[name].chunk.js',
    path: path.resolve(cwd, 'build'),
    publicPath: './build/',
    sourceMapFilename: '[name].map'
},

rules.push({
    test: /\.ts$/, 
        loaders: [
            'awesome-typescript-loader',
            'angular2-template-loader'
        ] ,
    test: /\.(ts|js)$/,
        loaders: [
            'angular-router-loader'
        ] ,
    include: [
        path.resolve(cwd, 'app')
    ]
});

Currently, only the main app.js and vendor.js files are being built (along with .map files), while the 0.chunk.js files are missing.

Upon navigating to the /reports-engine URL, I receive a 'page not found' error instead of the expected ReportsComponent.

I am unsure about what I might be overlooking.

Answer №1

Introducing the ReportEngine Module:

export const routes: Routes = [
  {
    path: '', 
    component: ReportsComponent,
    children: [    
      { 
        path: 'account', 
        component: Account
      },
      { 
        path: 'accounts-manage', 
        component: AccountsManage
      },
      {
        path: '**', 
        component: NotFoundComponent
      }
    ]
  }
];

To make it work, make the following change:

If you want to change the children's path from empty to something else, do this:

 children: [
      {
        path: '',
        component: AboutComponent
      }
 ]

If you're unsure, please visit the link below for an easy guide on lazy loading:

https://scotch.io/courses/routing-angular-2-applications/lazy-loading

I hope this solution helps you.

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

Compiling TypeScript files with an incorrect path when importing, appending "index" at the end of the @angular/material library

I'm currently working on creating a library to collect and distribute a series of Angular components across various projects, with a dependency on angular/material2. My objective is to eventually publish it on npm. However, I've encountered an i ...

What is the best way to reorganize an object's properties?

Looking for a way to rearrange the properties of an existing object? Here's an example: user = { 'a': 0, 'b': 1, 'c': 3, 'd': 4 } In this case, we want to rearrange it to look like this: user = { &a ...

Managing updates with the spread syntax: Dealing with undefined or null properties

Let's take a look at this example method: GetCustomerWithPoints(customerId: number): Customer { const customer = this.customerService.getCustomer(customerId); const points = this.pointService.getPointsForCustomer(customerId); return {...custo ...

angular 2 : Unable to locate the variable named 'Response'

I encountered an issue while working on my angular 2 project: Error: Cannot find name 'Response'. The error seemed to originate from the following service: import { Injectable } from '@angular/core'; import { Http } from '@ang ...

What is the importance of a subclass providing services to a superclass in Angular?

While exploring some Angular code today, I stumbled upon this interesting snippet: export class ContentFormComponent extends FormBase { ... constructor( private authService: AuthService, private apiService: ApiService, private segmentService: Segme ...

What steps should I take to manage an error image that is not found in a directory on my computer?

I am currently working with a list that displays various information, along with an image search function in an img tag that looks for a specific image related to the information. However, some of the information does not have a corresponding image and I w ...

Generating dynamic text in Angular based on certain conditions

I am still learning about Angular. Can someone please explain how to make text dynamic based on a count? For example, if the count is greater than 2, the text should be "Teams," and if it is less than or equal to 2, the text should be "Team." Here is what ...

Customized interfaces utilizing generic components

Here is my simplified question. interface Identity{ name: string; } Next, we have a generic interface. interface State<T extends Identity>{ [T.name] : StateContainer<T> } Unfortunately, this approach fails and the following error is ...

Loading screen displayed while transitioning between routes within Angular

I have been struggling to implement a loading spinner in my project. How can I display a loading screen when changing routes in Angular? Here is the HTML code snippet: <div *ngIf="showLoadingIndicator" class="spinner"></div> ...

typescript error: Unable to access properties of an undefined value

I am facing an issue while trying to import a class in my TypeScript code. I have tried using private classA = new ClassA, but it's not working as expected and the result is undefined. Here is my code: import JWT from "../Utils/JWT" import { ...

Creating a table with a horizontal layout using Angular Material's mat-table

I am currently utilizing angular material 8.2.3 for my website. However, I have encountered a seemingly simple issue that has me stuck. I am looking to display a table horizontally instead of vertically. In my table, I only have two columns. Below is the ...

Discover the steps to implement user authentication with a combination of username, password, and token in an Angular 4

After developing a form using Angular 4, I encountered the need to send the form data via the post method with Angular 4. Testing with Postman showed that the data is being received correctly. To accomplish this, I must use Basic Auth with a username and p ...

A specialized solution designed to avoid loops in references

Is there a method to create a general solution that can prevent circular variables in JavaScript? This solution should be effective for any level of depth or type of circular reference, not limited to the variable itself... So far I've come up with t ...

Loading external templates in Angular2 with Webpack2

Attempting to integrate ngtemplate-loader in a project using AngularJs 2 and Webpack 2 is proving challenging. While this setup has been successful in Angular 1.x projects with Webpack 1.x, it encounters an error when running in the browser: Uncaught Type ...

The error encountered is: "Unable to modify the 'x' property as it is readonly for the '[object Array]' object."

I've attempted various methods to modify this problem, regardless of how it's explained on different Stack Overflow threads. I am faced with an obstacle where I have an array composed of objects, and my goal is to iterate through the array and mo ...

What causes the template to refresh when the input remains unchanged while employing the OnPush strategy?

Trying to understand this situation: @Component({ selector: 'app-test', template: `value: {{value|json}} <button (click)="setValue()">set</button>`, changeDetection: ChangeDetectionStrategy.OnPush }) export class TestComponent ...

What is the best way to reproduce the appearance of a div from a web page when printing using typescript in Angular 4?

Whenever I try to print a div from the webpage, the elements of the div end up on the side of the print tab instead. How can I fix this issue? Below is my current print function: print(): void { let printContents, popupWin; printContents = document.getEl ...

Display a button only when hovering over it

Seeking assistance for a simple task that is eluding me at the moment. I am currently using scss and trying to make a button only appear when hovered over. The button is hidden in the code snippet below, nested within a block alongside some svgs. Any hel ...

Unable to impose a restriction on the number input field limit

My input field has a type of "number" with the min and max attributes applied to limit user input. However, I am facing an issue where users can still enter values beyond the set limit. How can I prevent users from entering values above the specified lim ...

Utilize Firebase for Playwright to efficiently implement 'State Reuse' and 'Authentication Reuse'

In my testing environment, I want to eliminate the need for repeated login actions in each test run. My approach involves implementing 'Re-use state' and 'Re-use Authentication', but I've encountered a challenge with Firebase using ...