how to import a CommonJS module as an ECMAScript module All In One
CJS vs ESM
.mjs
import .cjs
module
cjs-module.cjs
const sum = (a, b) => a + b;
// export = sum;
// 'export =' can only be used in TypeScript files.ts(8003)
// ❌
// exports = sum;
// obj = {}
// sum = undefined
// ✅
// exports.sum = sum;
// console.log(`module inner sum`, sum);
// ✅
// module.exports = sum;
// ✅
module.exports = {sum};
esm-module.mjs
export const Add = (a, b) => a + b;
// ✅
// export default Add;
// ✅
export default {Add};
index.mjs
const log = console.log;
// ESM ✅
// import Add from './esm-module.mjs';
// import {Add as add} from './esm-module.mjs';
// log(`Add =`, Add);
// // Add = [Function: Add]
// log(`add =`, add);
// // add = [Function: Add]
import ESM from './esm-module.mjs';
import {Add as add} from './esm-module.mjs';
log(`ESM =`, ESM);
// ESM = { Add: [Function: Add] }
log(`add =`, add);
// add = [Function: Add]
const test1 = ESM.Add(3,4);
const test2 = add(3,4);
if(test1 === 7 && test2 === 7) {
log(`
标签:CommonJS,const,sum,mdx,module,how,Add,import
From: https://www.cnblogs.com/xgqfrms/p/16964865.html