バレル(Barrel)とは、複数のモジュールから1つの便利なモジュールにエクスポートをロールアップする方法です。バレル自体は、他のモジュールの選択されたエクスポートを再エクスポートするモジュールファイルです。
ライブラリ内の次のクラス構造を想像してみてください:
// demo/foo.tsexport class Foo {}// demo/bar.tsexport class Bar {}// demo/baz.tsexport class Baz {}
バレルがなければ、ユーザーは3つのインポート文を必要とするでしょう:
import { Foo } from '../demo/foo';import { Bar } from '../demo/bar';import { Baz } from '../demo/baz';
代わりに、以下を含むdemo/index.ts
バレルを追加することができます:
// 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
今、ユーザーは必要なものをバレルからインポートできます:
import { Foo, Bar, Baz } from '../demo'; // demo/index.ts is implied
*
をエクスポートする代わりに、モジュールを名前でエクスポートすることができます。たとえば、baz.ts
に次のような機能があるとします。
// demo/foo.tsexport class Foo {}// demo/bar.tsexport class Bar {}// demo/baz.tsexport function getBaz() {}export function setBaz() {}
getBaz
/setBaz
をdemoからエクスポートしたくない場合、代わりに別名でそれらをインポートし、その別名でエクスポートすることで変数に入れることができます:
// 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
そして今、ユーザーは次のようになります:
import { Foo, Bar, baz } from '../demo'; // demo/index.ts is implied// usagebaz.getBaz();baz.setBaz();// etc. ...