commonJS 모듈을 esm방식으로 import할 경우, 컴파일 결과에
__importStar
와__importDefault
를 추가해주는 옵션.
import moment from 'moment';
moment();
moment
의 경우, commonJS 모듈로 export하기 때문에 위와 같이 작성하면 밑줄과 함께 에러를 알려준다.
node_modules/moment/ts3.1-typings/moment.d.ts:784:1
export = moment;This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag.
(이 모듈은 'export ='를 사용하여 선언되었으며 'esModuleInterop' 플래그를 사용하는 경우에만 기본 가져오기와 함께 사용할 수 있습니다.)
이를 해결하기 위해 아래와 같이 수정할 수 있다.
import * as moment from 'moment';
moment();
하지만 문제는 esm 스펙 상으로, *
를 사용한 import 결과는 object
만 가능하기 때문에 동작하지만 올바른 방식이라고 볼 수 없다.
따라서 tsconfig에 "esModuleInterop": true
를 추가함으로서 해결할 수 있다.
// 컴파일 전
import moment from 'moment';
// 컴파일 후
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const moment_1 = __importDefault(require("moment"));