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

Namespace (그리고 왜 ESM 이 이겼나)

~7 min · modules, namespaces, legacy, history

Level 0Curious
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete
"Namespace 가 옛 TypeScript. ES module 이 그 일 가져가서 더 잘 했어."

Namespace 가 뭐

TypeScript 의 `namespace` keyword 가 파일 안에서 또는 (reference tag 와 함께) 파일 가로질러 선언을 단일 이름 아래 group. namespace Math { export function add() { ... } } 가 `Math` namespace 만듦; `Math.add()` 로 멤버 접근. 같은 scope 의 여러 `namespace Math` 선언이 merge.

Namespace 가 ES module 보다 앞섬. JavaScript 가 표준 답 가지기 전 '전부 global scope 에 안 두고 코드 어떻게 조직?' 에 대한 TypeScript 의 원조 해결.

왜 ESM 이 이겼어

ES module 이 namespace 를 능가한 이유:

  • JavaScript 표준. ESM 이 언어의 일부. Namespace 가 TypeScript 전용.
  • Bundler-friendly. Tree-shaking 이 ESM import 에 작동; namespace 가 통째로 ship.
  • 파일-scoped. ESM 의 자연 단위가 파일. Namespace 가 명시 group 필요.
  • 정적 분석. Tool (linter, bundler, IDE) 이 import 분석 가능; namespace 가 더 opaque.

새 코드엔 `.ts` source 에서 `namespace` 절대 안 써. ES module 대신 써.

Namespace 가 여전히 나타나는 곳

Legacy library 의 `.d.ts` 파일의 `namespace` 선언: jQuery 의 타입, Lodash 의 pre-ESM 타입, ESM 시대 전의 큰 `@types/...` 패키지. 읽을 거; 안 쓸 거. Modern library 타입 정의 다 ES module 써.

Namespace 가 읽기-전용 역사. 옛 `.d.ts` 파일에서 보면 문법 알아봐; 자기 코드에 손 안 뻗어.

Code

Namespace vs ES module — 같은 모양, 다른 메커니즘·typescript
// Legacy: namespace.
namespace MyApp {
  export function init() { /* ... */ }
  export class Config { /* ... */ }

  export namespace Utils {
    export function helper() { /* ... */ }
  }
}

MyApp.init();
MyApp.Utils.helper();

// Modern: ES module.
// init.ts
export function init() { /* ... */ }

// config.ts
export class Config { /* ... */ }

// utils.ts
export function helper() { /* ... */ }

// app.ts
import { init } from './init';
import { Config } from './config';
import { helper } from './utils';

init();
helper();

External links

Exercise

튜토리얼이나 legacy codebase 의 작은 namespace 된 module 들고 와. ES module 로 다시 써 — logical 단위마다 한 파일, named export, index.ts barrel. 잃은 거 적어 (아마 아무것도).
Hint
Namespace 안 각 export 가 자기 파일의 export 됨. namespace wrapper 가 완전히 사라짐. Import 가 namespace.member 에서 named ES import 로 바뀜.

Progress

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

댓글 0

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

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