The Daily TIL

February 13, 2019 by AndyAndyjavascripttypescript

Barreling

The practice of rolling up a bunch of ES modules in a directory into a single group of named exports, using index.js.

Example

if you have…

// demo/foo.ts
export class Foo {}
// demo/bar.ts
export class Bar {}
// demo/baz.ts
export default Baz

…then instead of doing…

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

…you can create a Barrel that rolls up all of these separate modules…

// demo/index.ts
export * from './foo'; // re-export all of its exports
export * from './bar'; // re-export all of its exports
export { default as Baz } from './baz'; // re-export default export

…into a single module with multiple named exports…

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

References