how babel compiler convert ESM to CJS In Depth All In One
babel compiler 编译器实现原理
TypeScript esModuleInterop
ES Module Interop / ES 模块互操作
tsconfig.json
{
"compilerOptions": {
"jsx": "react",
"target": "es2015",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,// ✅
"forceConsistentCasingInFileNames": true,
"noImplicitAny": false,
"strictPropertyInitialization": false,
"downlevelIteration": false,
"noImplicitOverride": true
}
}
https://www.typescriptlang.org/tsconfig/#esModuleInterop
https://www.typescriptlang.org/zh/tsconfig#esModuleInterop
https://www.typescriptlang.org/play
https://stackoverflow.com/questions/56238356/understanding-esmoduleinterop-in-tsconfig-file
demos
ESM
// ESM
export const a = 1;
export const b = 2;
export const c = (str) => console.log(str);
export default () => {
return 3;
};
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = exports.b = exports.a = void 0;
const a = 1;
exports.a = a;
const b = 2;
exports.b = b;
const c = str => console.log(str);
exports.c = c;
var _default = () => {
return 3;
};
exports.default = _default;
CJS
// CJS
module.exports = {
a: 1,
b: 2,
c: (str) => console.log(str),
default: function(){return 3;}
}
"use strict";
// CJS
module.exports = {
a: 1,
b: 2,
c: str => console.log(str),
default: function () {
return 3;
}
};