C.W.K.
Stream
Lesson 01 of 05 · published

ES Module: import, export, default

~9 min · modules, esm, imports

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Module 마다 파일 하나. 필요한 거 import; 다른 사람 필요한 거 export."

ESM 모델

ES Module 에 각 파일이 자기 scope 가진 자기 module. Top 레벨 선언 변수가 `export` 안 하면 파일에 private. 다른 파일에서 쓰려면 `import`. Global namespace 없음; 모든 게 scoped.

이게 표준 JavaScript module 시스템. TypeScript 가 직접 채택 — 특별 문법 없음, transpilation 해킹 없음 (modern 환경 target 할 때). TypeScript 에 쓰는 같은 `import`/`export` 가 modern Node.js, Bun, Deno, 브라우저에 native 실행.

Named export vs default export

Named: export function greet() { ... }; import { greet } from './mod' 으로 import. 이름이 export site 에 고정; `as` 로 import 에 alias 가능.

Default: export default class Foo { ... }; import Foo from './mod' 으로 import. Importer 가 이름 선택. Module 당 default 하나.

Modern 스타일 가이드가 named export 로 기움 — import 가로질러 이름 일관 유지, bundler 와 더 나은 tree-shaking 지원, rename-symbol IDE 액션으로 refactoring 안정적. Default export 가 일부 library (예: React 자체) 에 역사적 이유로 남음.

Re-export

export { greet } from './mod' 가 local 로 import 없이 다른 module 에서 re-export. 디렉토리의 public API 통합하는 `index.ts` barrel 파일에 흔함.

Named export 가 default. 큰 codebase 에 더 잘 scale. Module 이 진짜로 단일 primary export 가질 때 (예: React component 파일) 만 default export 손 뻗어.

Code

Named export, default export, re-export·typescript
// math.ts — 여러 named export.
export function add(a: number, b: number): number { return a + b }
export function sub(a: number, b: number): number { return a - b }
export const PI = 3.14159;

// main.ts
import { add, sub, PI } from './math';
import * as math from './math';            // namespace import
import { add as plus } from './math';      // alias

add(1, 2);            // 3
math.PI;              // 3.14159
plus(1, 2);           // 3 — 같은 함수, 다른 이름

// component.ts — default export.
export default function Button() { /* ... */ }

// app.ts
import Button from './component';           // import 이름 너가
import AnyName from './component';           // 작동도 함 — default export 가 이름 유연

// Barrel 에서 re-export.
// index.ts
export { add, sub, PI } from './math';
export { default as Button } from './component';

External links

Exercise

3 파일 가진 폴더 만들어: add.ts, sub.ts, index.ts. 첫 2개가 함수 export; index 가 둘 re-export. 4번째 파일에서 index 로부터 import. Re-export 통해 타입이 옳게 흐르는지 확인.
Hint
Barrel 패턴 (디렉토리 모든 거 re-export 하는 index.ts) 이 library 가 public API 노출하는 법. Consumer 가 한 자리에서 import; 디렉토리 구조가 커튼 뒤에서 자유롭게 바뀜.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.