angularlazy-loadingangular8angular2-providers

Angular 8 Lazy Loading. Questions regarding: imports, entryComponents and providers


i have exceeded the 2MB mark a while ago, so i decided to implement Lazy loading to deal with my hefty batches. Therefore I have questions regarding imports, entryComponents and providers. To water all of them down into one question:

What do i import into app-routing.module.ts and what do import into login-routing.module.ts

since i use:


This my app-routing.module.ts:

const routes: Routes = [
  {
    path: '',
    component: AppComponent,
    children: [
      {
        path: '',
        pathMatch: 'full',
        redirectTo: '/login'
      },
      {
        path: '**',
        component: LoginComponent
      },
      {
        path: 'login',
        loadChildren: () => import('./account/login/login.module').then(m => m.LoginModule)
      }
    ]
  }
@NgModule({
  imports: [RouterModule.forRoot(routes, {useHash: true})],
  exports: [RouterModule]
})
export class AppRoutingModule { }

  This is my login-routing.module.ts:

const routes: Routes = [
  {
    path: '',
    component: LoginComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class LoginRoutingModule { }


Solution

  • This is one of those things where it depends on your use case. To reduce bundle sizes, ideally you're pushing everything as far down in your module tree as you can. So you App.Module would have very little in it, and the majority of your imports/declarations/providers/entry components would be in your feature module. This would include not injecting your services in the root unless you need to, and instead setting them up in a feature modules providers array.

    There are tradeoffs that need to be considered though. For example ideally with your Angular material modules you'd import them in your feature modules, but if you're going to have a lot of feature modules it is a bit of an annoyance to have to go into the module and add an import for each Material Module that you need in your feature module. On the flipside though for your Login Module you likely only need a few Material Modules, while your entire application may need a bunch of them.

    So to summarize, if your bundle size is your main concern push everything as deep as you can into your module tree. Just be aware that you're taking a slight hit to ease of development.

    So for the things that you mentioned (Angular Modules, Angular Material Modules, Services, other NPMs) you'd want to push them as far down into the module tree as you can. Keep in mind that for Singleton services you will want them in your app.module so they remain Singleton services. If you move them into the providers array in feature modules then they will all get their own instance. Another notable example is the HttpClientModule which you only want to import once in the root.