index.ts 파일을 “통(barrel)”처럼 만들어두면, 상위 코드에서 폴더 경로만으로 필요한 모듈을 한 번에 가져올 수 있어요 😉components/
Button/
Button.tsx
IconButton.tsx
index.ts ← Barrelsindex.ts 내부export { default as Button } from "./Button";export { default as IconButton } from "./IconButton";import { Button, IconButton } from "components/Button";처럼 간단하게 사용 가능 👍1. import 문이 간결해진다
2. 폴더 구조가 한눈에 보인다
index.ts만 보면 “이 폴더 안에 어떤 모듈이 모여 있는지” 바로 파악할 수 있어요.3. 리팩터링이 편해진다
index.ts만 수정하면 돼요.4. 의존성 트리(Dependency Tree)가 깔끔해진다
1. 바렐 파일이 너무 커질 수 있다
index.ts도 길어져 관리하기 번거로워질 수 있어요.2. 트리 쉐이킹(Dead Code Elimination) 주의
export * from "./A"; 같은 방식으로 모든 걸 일괄 re‐export하면, tree‐shaking이 제대로 동작하지 않을 수 있어요3. 순환 참조(Circular Dependency) 위험
4. 바렐에만 의존 경로가 집중됨
1. 바렐 크기 관리
2. 명시적 재내보내기(explicit export)
export * from "./SomeModule"; 대신 export { default as SomeModule } from "./SomeModule";
export type { SomeType } from "./SomeModule";
와 같이 개별 export를 사용하면, tree‐shaking이 더 잘 동작해요.
3. 순환 참조(Avoid Circular Dependency)
index.ts는 같은 폴더 내부의 모듈만 재내보낸다”는 원칙을 지키면 순환 의존성 문제를 피할 수 있어요.4. 폴더/파일 네이밍 일관성
components/
Button/
Button.tsx
IconButton.tsx
index.ts
이런 식으로 네이밍하면 누구나 구조를 쉽게 이해할 수 있어요.
5. 번들러 설정 확인
package.json에 "sideEffects": false 옵션을 추가하거나, Webpack/Rollup/Vite 설정에서 tree‐shaking 관련 옵션을 확인해 주세요.src/
components/
Button/
Button.tsx
IconButton.tsx
MenuButton.tsx
index.ts
Modal/
BaseModal.tsx
ConfirmModal.tsx
index.ts
components/Button/index.ts export { default as Button } from "./Button";
export type { ButtonProps } from "./Button";
export { default as IconButton } from "./IconButton";
export type { IconButtonProps } from "./IconButton";
export { default as MenuButton } from "./MenuButton";
export type { MenuButtonProps } from "./MenuButton";
// Before
import Button from "components/Button/Button";
import IconButton from "components/Button/IconButton";
// After
import { Button, IconButton } from "components/Button";
src/
types/
User.ts
Post.ts
Comment.ts
index.ts
types/index.tsexport * from "./User";
export * from "./Post";
export * from "./Comment";
import { User, Post, Comment } from "types";
| 구분 | 장점 | 단점 |
|---|---|---|
| 가독성 | - import 문이 간결해지며 코드가 깔끔해집니다. | - 바렐 파일 자체가 비대해지면 관리하기 어려워집니다. |
| 유지보수 | - 파일명 변경, 모듈 추가/삭제 시 index.ts만 수정하면 됩니다. | - 잘못 구성된 바렐은 순환 의존성(circular dependency)을 유발할 수 있습니다. |
| 의존성 관리 | - 번들러가 의존성 트리를 깔끔하게 정리해 줍니다. | - export * from ... 방식으로 모든 걸 re-export하면 tree-shakng이 제대로 안 될 수 있습니다. |
| 리팩터링 | - 필요한 모듈만 올바로 export해 두면 번들 크기가 줄어듭니다. | - 사이드 이팩트(side effect)가 있는 모듈을 바렐을 통해 잘못 로딩하면 예기치 않은 버그가 발생할 수 있습니다. |
1. TypeScript 공식 문서
2. Webpack 공식 문서
3. Vite 공식 문서
4. 블로그/아티클
✨ 정리 끝! ✨
바렐 패턴을 적절히 활용하면 import 문이 깔끔해지고, 유지보수·리팩터링이 한결 수월해집니다.
하지만 과도한 바렐 사용이나 순환 의존성, tree‐shaking 누락 등에 주의하면서 상황에 맞게 적용하세요! 😎🛠
Happy Coding! 🚀