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:
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
Named exports
Instead of exporting *, you can choose to export the module in a name. E.g., assume that baz.ts has functions:
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. ...