Tuesday, July 26, 2016

Angular2: Barrel

Angular2 Barrel is a way to encapsulate multiple module export into single unit. It helps to reduce multiple import statements in module.  It’s index.ts or index.d.ts file where modules are exported. Now to import modules we don’t need to import them separately. This barrel is gateways where we can import all the modules are re-exported.

According to angular.io documentation “A barrel is a way to rollup exports from several modules into a single convenience module. The barrel itself is a module file that re-exports selected exports of other modules.


Let’s say we have three modules dashboard.component.ts, dashboard.routes.ts, dashboard.service.ts. also we have index.ts(Barrel).

now in index.ts(Barrel) we have the code as 

export * from './dashboard.component';
export * from './dashboard.routes';
export * from './dashboard.service';

dashboard.component.ts
import { Component} from '@angular/core';
@Component({……})
export class DashboardComponent {  constructor() {}}

dashboard.routes.ts
import { RouterConfig } from '@angular/router';
export const DashboardRoutes: RouterConfig = [  ……];

dashboard.service.ts
import { Injectable } from '@angular/core';
@Injectable()
export class DashboardService {  constructor() {}} 

Now I have to use above module in app component.  So I will be importing without barrel into app.component
import { DashboardComponent } from ' dashboard.component’;
import { DashboardRoutes } from ' dashboard. routes’;
import { DashboardService } from ' dashboard. service’;
As we can see we need to write three line of code. assume if we have 10-20 modules exported from same same place. Now with barrel we can write the same import statement as 
 import { DashboardComponent, DashboardRoutes,  DashboardService } from ' dashboard;
Or
import * as dash from ' dashboard; 
Again "import * as dash from ' dashboard;" is not suggested as while compiling it will import all the modules present with barrel even if that is not required. its better to import specific modules.