ougi FE

Barrel export 패턴이란? 본문

카테고리 없음

Barrel export 패턴이란?

ougi 2025. 2. 9. 01:29
728x90

오늘은 깔끔한 코드를 작성하는 것으로 고민을 하다가

Barrel export 패턴에 대한 글을 보게 되어서 이렇게 글을 쓰게 되었습니다


Barrel export 패턴이란?

Barrel export 패턴은 여러 개의 모듈을 하나의 진입점(entry point)에서 모아서 export하는 방식이라고 합니다

이 방식을 사용하면 import문을 더욱 더 깔끔하고 간결하게 만들 수 있다고 합니다


사용 예시

먼저 폴더 구조를 말씀 드리겠습니다

src/
  components/
    	  footer.tsx
          header.tsx
          index.ts

 

 

원래 Barrel export 패턴을 사용하지 않고 하려면 이런 식으로 import 해야 했습니다

import Header from 'src/components/footer';
import Header from 'src/components/header';

 

하지만 Barrel export 패턴을 사용하면 한번에 한곳에서 불러올 수 있습니다

import { Button, Input, Modal } from './components';

 

저렇게 깔끔하게 import 하기 위해서는 index.ts에서 export를 저런 식으로 해주시면 됩니다

// index.ts

export { default as Footer } from './footer';
export { default as Header } from './header';

 

이름을 그냥 그대로 하고 싶다면 이런 식으로 하시면 됩니다

export * from './header';
export * from './footer';

글을 마치며

이렇게 더 깔끔하게 import를 관리할 수 있는 Barrel export 패턴에 대해서 알아보았는데 

지저분한 import들을 정리할 수 있다는 것에 굉장히 기뻤던 거 같습니다

글을 읽어주셔서 감사합니다

 

참고

https://basarat.gitbook.io/typescript/main-1/barrel

 

Barrel | TypeScript Deep Dive

TIPsBarrel 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: Copy// demo/foo.t

basarat.gitbook.io

 

728x90