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';

index.ts is similar index.js in nodejs or index.html is web site hosting.

So when you say import {} from 'directory_name' it will look for index.ts inside the specified directory and import whatever is exported there.

For example if you have calculator/index.ts as

export function add() {...}
export function multiply() {...}

You can do

import { add, multiply } from './calculator';

Tags:

Angular