Angular 2 Barrel Using Barrel

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

For example without a barrel, a consumer would need three import statements:

import { HeroComponent } from '../heroes/hero.component.ts';                                
import { Hero }          from '../heroes/hero.model.ts';                                      
import { HeroService }   from '../heroes/hero.service.ts';

We can add a barrel by creating a file in the same component folder. In this case the folder is called 'heroes' named index.ts (using the conventions) that exports all of these items:

export * from './hero.model.ts';   // re-export all of its exports
export * from './hero.service.ts'; // re-export all of its exports                           
export { HeroComponent } from './hero.component.ts'; // re-export the named thing

Now a consumer can import what it needs from the barrel.
import { Hero, HeroService } from '../heroes/index';

Still, this can become a very long line; which could be reduced further.

import * as h from '../heroes/index';

That's pretty reduced! The * as h imports all of the modules and aliases as h



Got any Angular 2 Question?