###概述 .tsconfig 文件中esModuleInterop:ture 什么意思? let's go!
问题发生在 es6模块引入commonjs模块时
//moment/index.js commonhs
exports.moment = moment
// 我们的ts 必须这样引入
import * as moment from 'moment'
moment(); // not compliant with es6 module spec
// 和上变等价
const moment = require("moment");
moment();
使用 esModuleInterop=true 我们可以在es6中导入commonjs.即
// ts文件
import moment from 'moment'
moment();
// esModuleInterop:true 转换成这样
const moment = __importDefault(require('moment'));
moment.default();
//__importDefault 函数
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
__importStar做一样的事, - es6直接返回,转换commonjs 成为带有default的对象(commonjs 导出本身就是对象)
// ts代码
import * as moment from 'moment'
// 转换后的js代码
const moment = __importStar(require("moment"));
// note that "moment" is now uncallable - ts will report error!
// __importStar 方法
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
allowSyntheticDefaultImports:
Allow default imports from modules with no default export.
This does not affect code emit, just typechecking
不管代码导出,只做类型检查,
In moment typings we don't have specified default export, and we shouldn't have,
beacuse it's available only with flag esModuleInterop on.
//在esModuleInterop = true时,从第三方没有default导出的库中导入到es6模块(ts)中,
allowSyntheticDefaultImports 不报错
So allowSyntheticDefaultImports just won't report error if we want to import
default from thrid party module which don't have default export.