Coming soon!

Angular2 Barrels

When coding an Angular2 application you quickly notice that your import statements can become cumbersome. This is where Angular2 jumps in with their concept called 'Barrels'. In the documentation, a barrel is defined as: "A barrel is a way to rollup exports from several ES2015 modules into a single convenience

  • Angular2

By Joris Brauns · 8/13/2016 9:38:52 AM (Original Post)

Angular2 Barrels

When coding an Angular2 application you quickly notice that your import statements can become cumbersome. This is where Angular2 jumps in with their concept called 'Barrels'.

In the documentation, a barrel is defined as:

"A barrel is a way to rollup exports from several ES2015 modules into a single convenience ES2015 module. The barrel itself is an ES2015 module file that re-exports selected exports of other ES2015 modules."

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

So that's it, if you have any comments or improvements which you would like to share feel free to leave a comment behind!


  • Angular2

By Joris Brauns · 8/13/2016 9:38:52 AM (Original Post)

Share this blogpost

Looking for talent?

Fill in the form below and we’ll get back to you as soon as possible.

Oops. You seem to have written your full name in invisible ink. Please enter it so we can read it. Oops. You seem to have written your company in invisible ink. Please enter it so we can read it. It seems your e-mail doesn’t exist. Please enter a real one so we can contact you. Oops. You seem to have written your telephone in invisible ink. Please enter it so we can read it.