Translate

Thursday, January 10, 2019

How to Modularize an Angular Application


Source: https://dzone.com/articles/howto-modularize-an-angular-application-by-example
This article shows how lazy loaded Angular modules can be used to bring down the initial download size of an application.

Starting Point

The starting point is the AngularAndSpring project. It is an Angular 7 application with Material Components and a reactive Spring Boot backend. The initial download was more than 1.6 MB in size. The reason for the size of the initial download is that the app module includes all the code of the dependencies that are needed by the whole application. The goal is to create a smaller app module that starts with just a splash component and the services that are needed by more than one module. Then the application lazy loads the modules for the routes the user navigates to. The application has three parts:
  • The overview table. That shows a table of cryptocurrency quotes and has the login.
  • The details pages. That shows the current details of the quote and a chart.
  • The orderbook page. That shows the current orderbooks and requires to be logged in.
Each of the parts will become a module with one or more components. The modules will have only the required imports and be loaded if the user navigates to their route.

Modules

To bring down the size of the initial download, the lazy loaded modules of Angular are used. The modules are generated with the Angular CLI and the components are moved in the modules. TypeScript types help to do the refactoring. The required imports for the modules need to be added and the routes need to be created.
To add the modules, the Angular CLI was used:
ng generate module details --routing
ng generate module orderbooks --routing
ng generate module overview --routing
That generated the modules with module and route files inside of their directories.

Overview Module

The components quoteoverview and login have been moved into the module directory.
The route of the module is defined in the file overview-routing.module.ts:
const routes: Routes = [{
    path: '',
    component: QuoteoverviewComponent
    }];
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class OverviewRoutingModule { }
Lines 1-4 define the empty path for the quoteoverview component.
Line 8 defines the route to be imported as a child route of the module.
The overview module has only one route because the login component is a modal panel. It is shown if you click on the login button.
The module is defined in the file overview.module.ts:
@NgModule({
    entryComponents: [
                      LoginComponent
                    ],
    imports: [
      CommonModule,
      OverviewRoutingModule,
      MatTableModule,
      MatToolbarModule,
      MatTabsModule, 
      MatButtonModule,
      MatDialogModule,
      MatFormFieldModule,
      MatInputModule,
      FormsModule,
      ReactiveFormsModule
    ],
  declarations: [
      LoginComponent,
      QuoteoverviewComponent
                 ]
})
export class OverviewModule { }
Lines 2-4 define the entryComponent login to enable the modal panel of the login component.
Lines 5-17 define the modules needed by the two components.
Lines 19-22 register the two components in the module.

Details Module

The components BsdetailComponentIbdetailcomponentCbdetailComponent, and BfdetailComponenthave been moved in the Module directory.
The routes of the module need to be defined in the file details-routing.module.ts:
const routes: Routes = [
                        {path: 'bsdetail/:currpair', component: BsdetailComponent},
                        {path: 'ibdetail/:currpair', component: IbdetailComponent},
                        {path: 'cbdetail/:currpair', component: CbdetailComponent},
                        {path: 'bfdetail/:currpair', component: BfdetailComponent},
                        ];
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class DetailsRoutingModule { }
Lines 1-6 define the subroutes of the module. The ':currpair' is a route variable that defines the currency pair requested.
Line 9 defines the import of the routes as child routes of the module.
The module is defined in the file details.module.ts:
@NgModule({
  imports: [
    CommonModule,    
    FormsModule,
    ReactiveFormsModule,
    MatToolbarModule,
    MatRadioModule,
    MatButtonModule,
    DetailsRoutingModule,
    ChartsModule,
  ],
  declarations: [
    IbdetailComponent,
    CbdetailComponent,
    BsdetailComponent,
    BfdetailComponent
  ]
})
export class DetailsModule { }
Lines 2-10 define the modules that are required by the components.
Lines 11-16 list the components of the module.

Overview Module

The overview module has only the orderbooks component. It is ony accessable after login so it is not needed on the public part of the app.
The route is defined in the following code block:
const routes: Routes = [
{
    path: '',
    component: OrderbooksComponent
  }
];
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class OrderbooksRoutingModule { }
It is the same as in the overview module, execpt for the component.
The module is defined in the orderbooks.module.ts:
@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    MatToolbarModule,
    MatSelectModule,
    MatRadioModule,
    MatInputModule,
    MatCheckboxModule,
    MatButtonModule,
    MatListModule,    
    OrderbooksRoutingModule
  ],
  declarations: [    
    OrderbooksComponent    
  ]
})
export class OrderbooksModule { }
Lines 2-14 define the modules that need to be imported for the component.
Lines 15-17 registers the orderbooks component.

Application Module

The application module now has only the splash component and the services and is defined in the app.module.ts file:
@NgModule({
  declarations: [
    AppComponent,
    SplashComponent,
  ],
  imports: [    
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    HttpClientModule,
    MatProgressSpinnerModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Lines 2-5 list the components of the application module.
Lines 6-13 define the modules needed to show the SplashComponent and define the services.
The global routes are defined in the app-routing.module.ts file:
const routes: Routes = [
    {path: 'overview', loadChildren: './overview/overview.module#OverviewModule'},
    {path: 'details', loadChildren: './details/details.module#DetailsModule'},
    {path: 'orderbooks', loadChildren: './orderbooks/orderbooks.module#OrderbooksModule', canActivate: [AuthGuardService]},
    {path: '**', component: SplashComponent}
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Lines 1-6 define the global routes. The loadChildren entries reference the modules for the paths. The default path points to the Splash component. That loads the 'overview' path and shows a welcome message and a spinner while loading the overview module.
Line 9 defines the routes for the route module.

Summary

Modularizing the application has helped the startup performance and shows how bigger downloads can be split. In this case, the initial load was more than halved. If the files are gzipped it is below 300 kb.
TypeScript made it easy to split the code into ,odules. Splitting the templates was not as easy. The Angular compiler did not show the missing modules. The errors are shown at run time. It would be nice if Angular would have a feature that checks that all used modules are imported at compile time.
Splitting an existing application into modules is quite easy and takes only a reasonable amount of effort. The better approach is to start the development of an application with modules, placing related components in modules with a common base route and subroutes to the components. The required imports can then be added during the development process. That keeps the startup performance okay, with little extra cost.