반응형

타입스크립트의 모듈 시스템 이해하기

모듈의 기본 개념과 중요성

모듈은 독립적인 기능 단위로, 코드를 체계적으로 구성하는 핵심 요소입니다. 모듈 시스템을 사용함으로써 얻을 수 있는 주요 이점들은 다음과 같습니다:

  1. 유지 보수성 향상
    • 코드 중복을 최소화하여 버그 발생 가능성 감소
    • 기능별로 분리된 코드로 수정이 용이
  2. 전역 스코프 오염 방지
    • 각 파일이 독립적인 스코프를 가짐
    • 변수명 충돌 문제 해결
  3. 재사용성 증가
    • 모듈을 여러 프로젝트에서 재사용 가능
    • 코드의 재사용성과 이식성 향상

TypeScript의 두 가지 모듈 시스템

1. 외부 모듈 (External Modules)

ES6의 모듈 시스템을 기반으로 하며, importexport 키워드를 사용합니다.

// math.ts
export function add(x: number, y: number): number {
    return x + y;
}

export function multiply(x: number, y: number): number {
    return x * y;
}

// main.ts
import { add, multiply } from './math';

console.log(add(2, 3));      // 5
console.log(multiply(2, 3)); // 6

2. 내부 모듈 (Internal Modules / Namespace)

네임스페이스를 사용한 TypeScript 고유의 모듈화 방식입니다.

// validation.ts
namespace Validation {
    export interface StringValidator {
        isValid(s: string): boolean;
    }

    export class EmailValidator implements StringValidator {
        isValid(s: string): boolean {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return emailRegex.test(s);
        }
    }
}

// 사용하기
let emailChecker = new Validation.EmailValidator();

모듈 시스템의 특징 비교

ES Modules (외부 모듈)의 장점

  1. 현대적인 접근방식
    • ES6 표준을 따르는 방식
    • 대부분의 모던 도구들과 호환성이 좋음
  2. 트리 쉐이킹 지원
    • 사용하지 않는 코드를 제거하여 번들 크기 최적화
    • 더 효율적인 코드 관리 가능
  3. 명확한 의존성 관리
    • 의존성을 명시적으로 선언
    • 컴파일 시점에 의존성 체크 가능
// 명시적인 의존성 선언
import { Component } from './component';
import { Utils } from './utils';

export class MyComponent extends Component {
    constructor() {
        super();
        Utils.doSomething();
    }
}

Namespace (내부 모듈)의 특징

  1. 레거시 지원
    • 오래된 TypeScript 프로젝트와의 호환성
    • AMD/CommonJS 이전의 모듈화 방식
  2. 단일 파일 번들링
    • --outFile 컴파일러 옵션으로 단일 파일 생성
    • 간단한 프로젝트에서 유용
/// <reference path="validations.ts" />
namespace App {
    export class Main {
        start() {
            let validator = new Validation.EmailValidator();
            console.log(validator.isValid("test@email.com"));
        }
    }
}

현대적인 개발에서의 권장사항

  1. ES Modules 사용 권장
    • 새로운 프로젝트는 ES Modules 사용
    • 더 나은 도구 지원과 생태계 통합
  2. 점진적 마이그레이션
    • 기존 네임스페이스 기반 코드는 점진적으로 ES Modules로 전환
    • 호환성을 고려한 전환 계획 수립
  3. 모듈 시스템 일관성
    • 한 프로젝트 내에서 일관된 모듈 시스템 사용
    • 혼합 사용은 가급적 피하기

컴파일 설정과 모듈 시스템

Namespace

{
    "compilerOptions": {
        "target": "es5",
        "module": "amd",
        "outFile": "./dist/bundle.js",
        "rootDir": "./src",
        "strict": true
    }
}

ES Modules

{
    "compilerOptions": {
        "module": "es2015",        // ES Modules 사용
        "moduleResolution": "node", // 모듈 해석 방식
        "target": "es5",           // 출력 JS 버전
        "sourceMap": true,         // 소스맵 생성
        "outDir": "./dist"         // 출력 디렉토리
    }
}

이러한 현대적인 접근 방식을 통해 더 안정적이고 유지보수가 용이한 TypeScript 프로젝트를 구축할 수 있습니다.

반응형

+ Recent posts