0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[TypeScript] Barrelパターンを使用して、エクスポートを集約する

Last updated at Posted at 2024-06-05

Barrelパターンとは?

Barrel パターンは、複数のモジュールからエクスポートを一つのモジュールに集約するデザインパターンです。


Barrel パターンの利点

  1. 可読性の向上: 複数のモジュールを一つのファイルにまとめてエクスポートすることで、他のファイルからのインポートがシンプルになる
  2. インポートの一元管理: インポート文が統一され、シンプルになる

ディレクトリ

src/
├── moduleA.ts
├── moduleB.ts
└── index.ts

各ファイル

moduleA.ts:

export const CONSTANT_A = 'A';

moduleB.ts:

export interface InterfaceB {
  id: number;
  name: string;
}

index.ts:

export * from './moduleA';
export * from './moduleB';

インポート例

import { CONSTANT_A, InterfaceB } from './src';

Barrel パターンを使用しない場合

Barrel パターンを使用しない場合、それぞれのモジュールを個別にインポートする必要があります。

import { CONSTANT_A } from './src/moduleA';
import { InterfaceB } from './src/moduleB';

まとめ

Barrel パターンを使用することで、可読性/保守性が向上するので積極的に活用していきたい

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?