개념
TypeScript의 tsconfig.json 설정 중 하나로, CommonJS 모듈을 ES6 스타일로 불러올 수 있도록 도와주는 옵션
기본적으로 TypeScript는 CommonJS 모듈(module.exports = ...)과 ES6 모듈(export default ...)을 다르게 처리해. 그래서 CommonJS로 작성된 라이브러리를 import x from '패키지'처럼 ES6 스타일로 불러오려면 esModuleInterop: true를 설정해야 오류 없이 사용할 수 있어.
// esModuleInterop이 false일 때
import * as mkdirp from 'mkdirp';
mkdirp.sync('path'); // 이렇게 써야 함
// esModuleInterop이 true일 때
import mkdirp from 'mkdirp';
mkdirp.sync('path'); // 깔끔하게 default import 가능
테스트
lib.js (CommonJS 방식)
// CommonJS 모듈
module.exports = function greet(name) {
console.log(`Hello, ${name}`);
}
main.ts
import greet from './lib'; // 이 코드가 esModuleInterop 여부에 따라 다르게 컴파일됨
greet('TypeScript');
tsconfig.json
컴파일 결과 (esModuleInterop: false)
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var lib_1 = require("./lib");
(0, lib_1.default)('TypeScript'); // 이 줄에서 런타임 오류 발생
컴파일 결과 (esModuleInterop: true)
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var lib_1 = __importDefault(require("./lib"));
(0, lib_1.default)('TypeScript');
여기서 핵심은 __importDefault 함수. 이게 CommonJS 모듈을 감싸서 .default 속성을 만든다
'IT > typescript' 카테고리의 다른 글
[typescript] WeakRef (0) | 2024.12.28 |
---|---|
[typescript] AtLeastOneRequired (0) | 2024.12.16 |
[typescript] -? 의미 (0) | 2024.12.05 |
[typescript] fattenObject 함수 type 만들기 (0) | 2024.08.21 |
[typescript] infer (0) | 2024.08.14 |