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

Communication between parent and child components in Angular 2 using objects

When you create a parent component and a child component, if you assign a primitive value (string, number, boolean) to the child component, you need to create an @Input and an @Output with EventEmitter to enable two-way communication. This process seems st ...

Handling Concurrent HTTP Requests in Angular using RxJS (Independently Triggered)

Angular 6: Implementing Angular Multiple HTTP Requests with RxJS (for updatePhone and updateAddress) that are independent of each other but may or may not occur simultaneously. Scenario 1: When changes are made to address fields (such as address, state, c ...

Tips for developing a strongly-typed generic function that works seamlessly with redux slices and their corresponding actions

Currently, I am working with @reduxjs/toolkit and aiming to develop a function that can easily create a slice with default reducers. Although my current implementation is functional, it lacks strong typing. Is there a way to design a function in such a man ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

Resolving TypeScript errors when using the Mongoose $push method

It appears that a recent package upgrade involving mongoose or @types/mongoose is now triggering new typescript errors related to mongoose $push, $pull, $addToSet, and $each operators. For instance: await User.findByIdAndUpdate(request.user._id, { $ ...

There has been an error of type TypeError, as the property 'replace' cannot be read from a null value

I encountered a TypeError message, even though my application seems to be functioning properly. "ERROR TypeError: Cannot read property 'replace' of null" I'm struggling to understand how to fix this issue. Can someone provide me ...

How can I ensure I am receiving real-time updates from a Resolver Service by subscribing and staying in sync with the

How can I effectively implement this code without encountering an error? "Property 'resolve' in type 'DocumentaryResolverService' is not assignable to the same property in base type 'Resolve'." import { Documentary } from ...

Angular directive unit testing results in an Access to XMLHttpRequest error being thrown

Here is a custom directive example: @Directive({ selector: '[appTitleCase]', }) export class TitleCaseDirective { @HostListener('change', ['$event']) onChange($event: Event) { const titleCaseValue = TextHelpers.convert ...

Error: Unable to locate specified column in Angular Material table

I don't understand why I am encountering this error in my code: ERROR Error: Could not find column with id "continent". I thought I had added the display column part correctly, so I'm unsure why this error is happening. <div class="exa ...

Is there a way to customize the styles for the material UI alert component?

My journey with Typescript is relatively new, and I've recently built a snackbar component using React Context. However, when attempting to set the Alert severity, I encountered this error: "Type 'string' is not assignable to type 'Colo ...

dyld: Unable to locate symbol: _node_module_register

Embarking on my Angular2 learning journey with the help of this GitHub repository: https://github.com/angular/quickstart After running npm install, I attempted to launch the project in a browser using npm start. However, I encountered the following error: ...

Altering the background color of an individual mat-card component in an Angular application

Here is the representation of my mat-card list in my Angular application: <div [ngClass]="verticalResultsBarStyle"> <div class="innerDiv"> <mat-card [ngClass]="barStyle" *ngFor="let card of obs | async | paginate: { id: 'paginato ...

Detecting Errors in Angular Components Using Observers

In my component, I have the following code: this.authService.login4(this.email, this.password) .pipe(first()) .subscribe( data => { console.log(data); }, error => { ...

I have set up a custom ag-grid three times within a single component, however, only the first instance is properly initialized while the other two instances are not initialized

I have developed a custom ag-grid for reusability in my project. Initially, when I initialize the custom ag-grid in one component, it works perfectly as shown below: example.html <html> <body> <input type="text"> <md-app-aggrid [c ...

Issue with rendering images retrieved from JSON data

Struggling with displaying images in my Ionic and Angular pokedex app. The JSON file data service pulls the image paths, but only displays the file path instead of the actual image. Any ideas on what might be causing this issue? Sample snippet from the JS ...

The Unusual Behavior of Typescript Partial Interfaces

While reviewing the code in a repository I am currently working on, I stumbled upon something that seemed completely incorrect. Here is a snippet of what caught my attention. interface Car { make: string model: string } type SomeType = Partial<Car& ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

It appears that Stackblitz may have an outdated package.json file for older Angular projects, causing compatibility issues when running the project locally

Upon reviewing the package.json files for older Angular projects on Stackblitz, I have observed a pattern where Angular9 is listed under devDependencies while dependencies include older versions such as "@angular/core": "7.2.2" or "@angular/core": "6.1.10" ...

SSR routing with parameters in Angular Universal seems to be failing after intial navigation

I'm currently experiencing an issue with routing using path parameters: Navigation works perfectly when moving between categories initially, but once I navigate from one category to another, the routing doesn't update even though the URL in the ...

Encountering issues with Angular 12 optimized build, the error messages are sparse and offer little

While my project compiles without any issues in development mode with the build optimizer turned off, I encounter an error during production build: ✔ Browser application bundle generation complete. ✔ ES5 bundle generation complete. ✔ Copying assets c ...