Angular Newsletter By Techiediaries

Share this post
Using Barrel files with Angular
angularnewsletter.substack.com

Using Barrel files with Angular

Have you ever come across an index.ts file and wondered what it is?

Ahmed Bouchefra
Jun 29, 2021
Comment
Share

Have you ever come across an index.ts file and wondered what it is?

index.ts is a Barrel

A barrel is a name for an index.ts file. A barrel is a way to roll-up exports from several modules into a single module.

Imagine three modules in a heroes folder:

// heroes/hero.component.ts 
export class HeroComponent {}  // heroes/hero.model.ts 
export class Hero {}  // heroes/hero.service.ts 
export class HeroService {} 

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 to the heroes folder (called index by convention) 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 is implied 

Should I use barrels?

The simple answer is Yes. However, barrels were removed from the Angular style guide.

“Barrels now are far less useful and have been removed from the style guide; they remain valuable but are not a matter of Angular style.”

So if you want to follow the Angular Style Guide you should avoid them.

CommentComment
ShareShare

Create your profile

0 subscriptions will be displayed on your profile (edit)

Skip for now

Only paid subscribers can comment on this post

Already a paid subscriber? Sign in

Check your email

For your security, we need to re-authenticate you.

Click the link we sent to , or click here to sign in.

TopNewCommunity

No posts

Ready for more?

© 2022 Ahmed Bouchefra
Privacy ∙ Terms ∙ Collection notice
Publish on Substack Get the app
Substack is the home for great writing