Barrel

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

Imagine the following class structure in a library:

  1. // demo/foo.ts
  2. export class Foo {}
  3. // demo/bar.ts
  4. export class Bar {}
  5. // demo/baz.ts
  6. export class Baz {}

Without a barrel, a consumer would need three import statements:

  1. import { Foo } from '../demo/foo';
  2. import { Bar } from '../demo/bar';
  3. import { Baz } from '../demo/baz';

You can instead add a barrel demo/index.ts containing the following:

  1. // demo/index.ts
  2. export * from './foo'; // re-export all of its exports
  3. export * from './bar'; // re-export all of its exports
  4. export * from './baz'; // re-export all of its exports

Now the consumer can import what it needs from the barrel:

  1. import { Foo, Bar, Baz } from '../demo'; // demo/index.ts is implied

Named exports

Instead of exporting * you can chose to export the module in a name. Eg. assume that baz.ts has functions:

  1. // demo/foo.ts
  2. export class Foo {}
  3. // demo/bar.ts
  4. export class Bar {}
  5. // demo/baz.ts
  6. export function getBaz() {}
  7. export function setBaz() {}

If you would rather not export getBaz / setBaz from demo you can instead put them in a variable by importing them in a name and exporting that name as shown below:

  1. // demo/index.ts
  2. export * from './foo'; // re-export all of its exports
  3. export * from './bar'; // re-export all of its exports
  4. import * as baz from './baz'; // import as a name
  5. export { baz }; // export the name

And now the consumer would look like:

  1. import { Foo, Bar, baz } from '../demo'; // demo/index.ts is implied
  2. // usage
  3. baz.getBaz();
  4. baz.setBaz();
  5. // etc. ...