Modules
해당 핸드북에서는 import/export(ES Modules)와 CommonJS의 module.exports 문법을 다룹니다.
How JS Modules are Defined
최상단에 import 또는 export가 있어야 해당 파일을 module이라고 인지합니다.
Non-modules
JS에서는 import 선언문, export 그리고 최상단에 await가 없다면 스크립트로 간주합니다.
만약 import나 export 할 게 없는데 해당 파일을 모듈로 인식하게 하고 싶다면 export {}; 를 사용하면 됩니다.
Modules in TS
TS에서 모듈 기반 코드에 대해 고려하는 것
1. Syntax
2. Module Resolution
3. Module Output Target
ES Modul Syntax
// export default and import
export default function some(){};
import some from './something.js';
// export by omitting default
export function thing() {};
import { thing } from './something.js';
Additional Import Syntax
import some, { thing as any } from './something.js';
// all exported objects
import * from './something.js';
// all of the code
import './something.js';
TS Specific ES Module Syntax
타입도 export, import 할 수 있습니다.
export type any = {};
export type thing = {};
// 1. import type
import type { any, thing } from './anything.js';
// 2. inline type imports 버전 4.5
import { type any, type thing } from './anything.js';
type 키워드를 생략할 수 있지만, 가독성을 올려주고 Babel, swc 또는 esbuild와 같은 transpiler를 도와줍니다.
ES Module Syntax with CommonJS Behavior
import fs == require('fs');
CommonJS Syntax
Exporting
function some() {}
module.exports = {
some,
};
const { some } = require('./something.js');
CommonJS and ES Modules interop
TS's Module Resolution Options
module resolution은 import나 require 구문을 가져가고 문자열에서 어떤 파일을 참조할지 결정하는 과정입니다.
두 가지 접근을 제공합니다.
1. classic: 컴파일러 옵션 모듈이 commonjs가 아닌 경우 호환성을 위한 접근
2. node: node.js가 commonjs 모드에서 동작하고 .ts 와 .d.ts를 확인하는 접근
모듈 전략을 위해 다양한 tsconfig flag들이 있습니다.
TS's Module Output Options
- target: 코드의 유지와 이전 버전으로 downlevel 할지 결정합니다.
- module: 모듈이 각자 상호작용하기 위한 코드를 결정합니다.
TS namespaces
TS는 namespaces라고 불리는 본인의 모듈 포맷이 있습니다.
이렇게 핸드북에 있는 내용을 한 번 다 읽어 봤습니다만, 이해되지 않았던 내용도 있고 사용하지 않으니 까먹는 부분도 있습니다. 또한 제가 생각했던 유틸리티 타입은 다른 페이지에 있는 걸 확인했습니다. 앞으로 TS를 사용해 보면서 다시 보러 오겠습니다. 그때는 더 많은 부분이 이해되면 좋을 것 같습니다.
참고
'개발 > TS' 카테고리의 다른 글
| [TS] TS Doc Reference 1회독 - 2 (1) | 2025.07.18 |
|---|---|
| [TS] TS Doc Reference 1회독 (0) | 2025.07.16 |
| [TS] TS Doc Handbook 1회독 - 9 (0) | 2025.06.24 |
| [TS] TS Doc Handbook 1회독 - 8 (0) | 2025.06.20 |
| [TS] TS Doc Handbook 1회독 - 7 (0) | 2025.06.17 |