What are all the index.ts used for?

From the Angular.io v2’s archived glossary entry for Barrel*:

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.

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

The Angular scoped packages each have a barrel named index.

See also EXCEPTION: Can’t resolve all parameters


* NOTE: Barrel has been removed from more recent versions of the Angular glossary.

UPDATE
With latest versions of Angular, barrel file should be edited as below,

export { HeroModel } from './hero.model';  
export { HeroService } from './hero.service'; 
export { HeroComponent } from './hero.component';

Leave a Comment