본문 바로가기
Web/JavaScript

[Typescript] Module System

by llHoYall 2023. 8. 9.

이번 포스팅에서는 typescriptmodule에 대해 가볍게 살펴보겠습니다.

즉, 하나의 파일에서 정의된 내용을 다른 파일에서 가져다 사용하는 방법에 대해 공유드리겠습니다.

Default Export

하나의 module은 하나의 항목을 defaultexport할 수 있습니다.

// calc.ts
const add = (x: number, y: number): number => {
  return x + y;
};

export default add;

예제와 같이 add라는 함수를 default로 export 했습니다.

이제, 사용하는 부분을 살펴볼게요.

// main.ts
import myAdd from './calc';

console.log(myAdd(3, 4));

보시는 대로 default로 export한 것은 임의로 원하는 이름을 붙여서 사용할 수 있어요.

Named Export

이번에는 여러 항목을 export하는 방법을 살펴 보겠습니다.

// calc.ts
export const add = (x: number, y: number): number => {
  return x + y;
};

export const subtract = (x: number, y: number): number => {
  return x - y;
};

원하는 항목 앞에 export keyword를 붙여주기만 하면 됩니다.

// main.ts
import { add, subtract } from './calc';

console.log(add(3, 4));
console.log(subtract(7, 4));

이 경우에는 기본적으로 export된 이름을 그대로 사용해야 합니다.

// main.ts
import { add as myAdd, subtract as mySubtract} from './calc';

console.log(myAdd(3, 4));
console.log(mySubtract(7, 4));

as keyword를 사용하면 원하는 이름을 붙이는 것도 가능합니다.

다른 형태의 export에서도 사용 가능하니 필요한 경우 사용하시면 됩니다.

Namespace Export

이번에는 namespace를 지정하여 export 하는 방법을 살펴 보겠습니다.

다른 모듈에서 같은 이름으로 정의된 항목이 존재할 수 있기 때문에 이를 구분하기 위해 별도의 namespace를 지정하기 위해 사용합니다.

// calc.ts
export namespace calc {
  export const add = (x: number, y: number): number => {
    return x + y;
  };

  export const subtract = (x: number, y: number): number => {
    return x - y;
  };
}

이제 사용을 해보겠습니다.

// main.ts
import { calc } from './calc';

console.log(calc.add(3, 4));
console.log(calc.subtract(7, 4));

namespace를 불러온 후, 이를 통해 내부 함수를 호출할 수 있습니다.

이렇게 되면 동일한 이름의 항목이 존재하더라도 구분해낼 수 있게되죠.

Wildcard Export

Wildcard를 사용할 경우 export한 모든 항목을 한 번에 가져올 수 있습니다.

가독성의 이유로 권장되지 않기도 하지만, 소규모 개발 혹은 빠른 결과가 필요한 경우에는 편하게 사용할 수 있어요.

// calc.ts
export const add = (x: number, y: number): number => {
  return x + y;
};

export const subtract = (x: number, y: number): number => {
  return x - y;
};

필요한 항목들을 지정하여 export 합니다.

// main.ts
import * as calc from './calc';

console.log(calc.add(3, 4));
console.log(calc.subtract(7, 4));

이후 wildcard를 사용하여 불러온 후 사용하시면 되요.

단, 이 경우 as로 이름을 반드시 지정해줘야 합니다. 그렇지 않으면 ts(1005) 에러가 발생합니다.

Re-Export

다른 module에서 export한 것을 한 곳에 모아 package 형태로 export할 때 주로 사용합니다.

먼저, module들을 정의합니다.

// add.ts
export const add = (x: number, y: number): number => {
  return x + y;
};

// subtract.ts
export const subtract = (x: number, y: number): number => {
  return x - y;
};

이 module들을 한 데 모아서 package 형태로 export 합니다.

// calc.ts
export * from './add';
export * from './subtract';

이후, 이 모아진 module들을 사용하면 됩니다.

// main.ts
import { add, subtract } from './calc';

console.log(add(3, 4));
console.log(subtract(7, 4));

Conditional Export

조건에 따라 export를 할 수도 있습니다.

// calc.ts
const add = (x: number, y: number): number => {
  return x + y;
};

const subtract = (x: number, y: number): number => {
  return x - y;
};

let defaultExport: (x: number, y: number) => number;
if (true) {
  defaultExport = add;
} else {
  defaultExport = subtract
}
export default defaultExport;

예제와 같이 조건에 따라 다른 항목들을 export 할 수 있습니다.

// main.ts
import calc from './calc';

console.log(calc(3, 4));

이제 export된 항목을 사용하면, 조건에 따라 다른 항목을 가질 수 있습니다.

Wrap Up

이번에는 typescript의 module system에 대해 간략히 살펴 보았습니다.

설명한 내용은 모두 개별적인 게 아니라 서로 혼합해서 사용할 수도 있으니, 한 번 익혀두시고 두고두고 사용하세요.

'Web > JavaScript' 카테고리의 다른 글

[Next.js] Layout으로 공통 화면 구성하기  (2) 2024.02.17
[Next.js] Routing using App Router  (0) 2024.02.04
[Svelte] Template Syntax  (0) 2022.12.10
[Svelte] Getting Started with SvelteKit  (0) 2022.12.01
[JavaScript] Map Object  (0) 2022.07.14

댓글