Using Barrel files with Angular
Have you ever come across an index.ts file and wondered what it is?
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.