본문 바로가기
TypeScript

Module

by eddypark 2023. 8. 31.

- 재사용이 가능한 코드 조각을 의미한다.

- 자체 스코프 내에서 실행된다.

- 모듈에서 데이터를 불러오는 import와 모듈에서 데이터를 내보내는 export로 나누어져 있다.

(1) export

- 모듈의 변수, 함수, 타입 등을 외부 모듈이 사용할 수 있도록 표시한 키워드이다.

export var a = "wangi";       // export data
 
export function b(x, y) {     // export function 방법1 : 정의와 동시에 export
    return x + y;
}

function c(x, y) {            // export function 방법2 : 정의 후 함수 이름으로 export
    return x * y;
}
 
export { c };
 
export class d{               // export class
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

- as 키워드를 사용하여 이름을 변경할 수 있다.

function a(x, y) {  
    return x * y;
}
 
export { a as b };    // a 모듈을 b이름으로 export

- default키워드를 사용하여 기본 export를 할 수 있다.

export default function(x, y) {  // 함수 선언 앞에 default
    return x + y;
}

function a(x, y) {  
    return x + y;
}
export default a;                    // 함수 이름 앞에 default
 
function b(x, y) {
    return x + y;
}
export { b as default };             // as을 활용한 default

 

(2) import

- 다른 모듈에 있는 변수나 타입, 함수 등을 불러와 사용할 때 쓰는 키워드이다.

- 키워드 뒤의 괄호 안에 import 하고자 하는 것을 나열하고 from뒤에는 모듈명을 적으면 된다.

- as 키워드를 사용하여 이름을 변경할 수 있다.

- default키워드를 사용한 모듈을 import 할 때는 {}를 사용하지 않는다.

import { sum } from "./example.js";               // sum 모듈 하나만 import
import { sqrt, minus } from "./example.js";       // 여러모듈 import
import * from "./example.js";                     // 모든 모듈 import
import { add as a } from "./example.js";          // as를 이용한 이름 변경
import a, { b } from "./example.js";              // a모듈은 default로 export한 모듈이라 {}를 쓰지않는다. 

console.log(sum(1, 2));                           // 3
sum = 1;                                          // error 동일한 이름의 다른 변수 정의 할 수 없고, 새로운 값 할당도 불가.

 

(3) 상대 모듈 import와 비상대 모듈 import

- 상대적 import는 /, ./, ../로 시작

- 비상대적 import는 상대적 import를 제외한 나머지(보통 확장자이름이. ts 이거나. d.ts)

import { b } from "./moduleB" 조회 과정
상대 모듈 import (현재폴더만 탐색)
비상대 모듈 import (현재 폴더에서 발견 못하면 상위폴더로 이동)
/root/src/folder/moduleB.ts
/root/src/folder/moduleB.d.ts
/root/src/folder/moduleB.ts
/root/src/folder/moduleB.d.ts
/root/src/moduleB.ts
/root/src/moduleB.d.ts
/root/moduleB.ts
/root/moduleB.d.ts
/moduleB.ts
/moduleB.d.ts

'TypeScript' 카테고리의 다른 글

타입 앨리어스  (0) 2023.09.04
Generic  (0) 2023.09.01
Decorator  (0) 2023.08.30
Class  (0) 2023.08.30
TypeScript란?  (0) 2023.08.30