モジュールの再エクスポート(export from)
export ... from 構文を使うと、他のモジュールからインポートした値をそのまま再エクスポートできます。複数のモジュールをまとめて公開する際に便利です。
基本的な使い方
import してから export する代わりに、1行で再エクスポートできます。
// 従来の書き方(2行必要)
import { Button } from './Button.js';
export { Button };
// 再エクスポート(1行で済む)
export { Button } from './Button.js';再エクスポートした値は、そのモジュール内では使用できません。使用したい場合は別途 import が必要です。
名前付きエクスポートの再エクスポート
複数の値をまとめて再エクスポートできます。
// components/index.js
export { Button } from './Button.js';
export { Input } from './Input.js';
export { Modal } from './Modal.js';
export { Card, CardHeader, CardBody } from './Card.js';// 利用側
import { Button, Input, Modal } from './components';すべてを再エクスポート
export * を使うと、モジュールのすべての名前付きエクスポートを再エクスポートできます。
// math/index.js
export * from './basic.js'; // add, subtract など
export * from './advanced.js'; // sin, cos など
export * from './constants.js'; // PI, E などただし、デフォルトエクスポートは export * には含まれません。
デフォルトエクスポートの再エクスポート
デフォルトエクスポートを再エクスポートするには、名前を付ける必要があります。
// 名前付きとして再エクスポート
export { default as Button } from './Button.js';
// そのままデフォルトとして再エクスポート
export { default } from './Button.js';別名での再エクスポート
as を使って、名前を変更しながら再エクスポートできます。
export { Button as PrimaryButton } from './Button.js';
export { oldFunction as newFunction } from './legacy.js';バレルファイル(Barrel File)
複数のモジュールを1つのエントリーポイントにまとめるファイルを「バレルファイル」と呼びます。
// utils/index.js(バレルファイル)
export { formatDate, parseDate } from './date.js';
export { formatNumber, parseNumber } from './number.js';
export { debounce, throttle } from './function.js';
export * from './string.js';バレルファイルなし
import { formatDate } from './utils/date.js';
import { debounce } from './utils/function.js';バレルファイルあり
import { formatDate, debounce } from './utils';インポートパスがシンプルになり、内部構造の変更にも柔軟に対応できます。
注意点
名前の衝突
export * で複数モジュールを再エクスポートする際、同じ名前があるとエラーになります。
Tree Shaking への影響
バレルファイル経由でインポートすると、バンドラーによっては不要なコードが含まれる場合があります。
// エラーになる例
// a.js と b.js の両方に helper という名前がある場合
export * from './a.js';
export * from './b.js'; // エラー:helper が重複
// 解決方法
export * from './a.js';
export { helper as helperB } from './b.js';再エクスポートを活用することで、モジュールの公開 API を整理し、利用者にとって分かりやすいインターフェースを提供できます。