Barrels
In the Angular 2 Docs a Barrel is defined as:
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.
Import Clutter
Eventually when your application grows large, one of the problem that you are going to end up with is managing imports in a file. Lets says one of your Components needs a custom pipe, a couple of classes, one service and a bunch of custom directives. Here is how the import in that file would look like:
import { Component } from '@angular/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { MyPipe } from './pipes/my.pipe';
import { User } from './models/user';
import { Recepie } from './models/recepie';
import { ExceptionService } from './services/exception.service';
import { Config } from './config';
import { MyButtonDirective } from 'directives/my-button.directive';
import { MySuperLoaderDirective } from 'directives/my-super-loader.directive';
import { MyListDirective } from 'directives/my-list.directive';
Now that is a lot of import statements and you can easily anticipate that over time you will adding more imports. You may also import these same services, classes & directive etc again in some other component as well. Well, this is where Barrels come in to reduce import clutter.
Export Modules
Create a new file in a folder named shared
. Name the file index.ts
. In this file we will simply import and re-export other modules. Here is how its done:
export { * } from './pipes/my.pipe';
export { * } from './models/user';
export { * } from './models/recepie';
export { * } from './services/exception.service';
export { * } from './config';
export { * } from 'directives/my-button.directive';
export { * } from 'directives/my-super-loader.directive';
export { * } from 'directives/my-list.directive';
Now the export statement in our original file becomes:
import { Component } from '@angular/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated';
import { MyPipe,
User,
Recepie,
ExceptionService,
Config,
MyButtonDirective,
MySuperLoaderDirective,
MyListDirective} from './shared';
Nice? Well yes.You can do even better by importing everything and aliasing it under myapp
name:
import * as myapp from './shared';
// Usage:
let config = myapp.Config;
You can also just import it and it will be available in the current scope:
import from './shared';
// Usage:
let config = Config;