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:
// demo/foo.tsexport class Foo {}// demo/bar.tsexport class Bar {}// demo/baz.tsexport class Baz {}
Without a barrel, a consumer would need three import statements:
import { Foo } from '../demo/foo';import { Bar } from '../demo/bar';import { Baz } from '../demo/baz';
You can instead add a barrel demo/index.ts
containing the following:
// demo/index.tsexport * from './foo'; // re-export all of its exportsexport * from './bar'; // re-export all of its exportsexport * from './baz'; // re-export all of its exports
Now the consumer can import what it needs from the barrel:
import { Foo, Bar, Baz } from '../demo'; // demo/index.ts is implied
Instead of exporting *
, you can choose to export the module in a name. E.g., assume that baz.ts
has functions:
// demo/foo.tsexport class Foo {}// demo/bar.tsexport class Bar {}// demo/baz.tsexport function getBaz() {}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:
// demo/index.tsexport * from './foo'; // re-export all of its exportsexport * from './bar'; // re-export all of its exportsimport * as baz from './baz'; // import as a nameexport { baz }; // export the name
And now the consumer would look like:
import { Foo, Bar, baz } from '../demo'; // demo/index.ts is implied// usagebaz.getBaz();baz.setBaz();// etc. ...