ECMAScript 2015부터 Javascript에는 모듈 개념이 있고, Typescript는 이 개념을 공유한다. 모듈은 자체 스코프 내에서 실행되는데, 즉 모듈 내에서 선언된 변수, 함수, 클래스 등은 export
, import
를 사용하지 않으면 외부에서 보이지 않는다.
Javascript에서 사용하는 유명한 모듈 로더로는 CommonJS
모듈용 Node.js
의 로더와, 웹의 AMD
모듈용 RequireJS
로더가 있다.
Export
선언 export 하기
export
키워드를 추가해 모든 선언을 내보낼 수 있다.
First.ts
export interface PropTypes {
// ...
}
Second.ts
import { PropTypes } from './First';
export const number = 1;
export const Second = (props: PropTypes) => {
// ...
};
Export문
Export
문은 사용자를 위해 export
할 이름을 바꿔야 할 때 유용하다.
export const string = 'lee';
export const hello = () => {
// ...
};
export { hello as world }; // world로 이름 변경
Re-export 하기
다른 모듈을 확장하고 일부 기능을 부분적으로 노출한다. (외부 모듈 내보내기)
export { hello as world } from './hello'; // 다른 파일의 Hello를 export
export * from './Second'; // number, Second 내보내기
Import
단일 export를 import 하기
단일로 import 하거나, 이름을 변경할 수도 있다.
import { hello } from './Hello';
import { hello as world } from './Hello'; // 변수명 world로 import
전체 모듈을 단일로 import 하기
import * as test from './hello';
const func = test.hello();
부수효과만을 위한 import
권장되지는 않지만 단순히 다른 모듈에서 사용할 수 있도록 일부 전역 상태로 설정한다.
import './my-module.js';
타입 import 하기 (Importing Types)
Typescript 3.8 이전에는 import
를 사용하여 타입을 가지고 왔고, 3.8부터는 import type
도 사용 가능하다.
import { propTypes } from './hello'; // 일반적인 사용
import type { propTypes } from './hello'; // 명시적으로 import type 사용
Default export
default
키워드를 사용해 대표하는 모듈을 export
할 수 있다.
Hello.ts
export default 'hello';
Log.ts
import log from './Hello';
console.log(log); // 'hello'
*을 사용해 모두 export 하기 (Export all as x)
* as x
로 export
할 경우 외부에서 x
로 접근할 수 있다.
export * as utils from './utils';
// 외부 파일
import { utils } from './index';
export =와 import = require() (export = and import = require())
CommonJS
와 AMD
둘 다 일반적으로 모듈의 모든 exports를 포함하는 exports
객체의 개념을 가지고 있고 exports
객체를 단일 객체로 대체하는 기능도 지원하지만, export default
와 호환되지는 않는다. CommonJS
와 AMD
를 위해 export =
을 지원한다. 단일 객체를 지정하며, 클래스, 인터페이스, 네임스페이스, 함수 혹은 열거형이 될 수 있다.
export.ts
const hello = () => {
// ...
};
export = hello;
import
import hello = require('./export.ts');
'스터디' 카테고리의 다른 글
[Typescript] 네임스페이스 (namespace) (0) | 2023.07.14 |
---|---|
[Typescript] 모듈 해석 (0) | 2023.07.09 |
[Typescript] 유틸리티 타입 (1) | 2023.06.19 |
[Typescript] 제네릭 (Generics) (0) | 2023.06.12 |
[Typescript] 열거형 (Enums) (0) | 2023.06.11 |