了解了,我这边也做了一些测试,node 上确实是能够支持 ESM 模块以具名导入的方式导入 CJS 模块的,但是支持也是相对有限,
例如下边例子中的变量 d
// main.mjs
import { a, b, c, d } from './test.cjs';
console.log(a, b, c, d)
setTimeout(() => {
console.log(a, b, c, d) // 这里的 d 依旧是 undefined,是不支持 live binding 的
}, 2000)
// test.cjs
module.exports.a = 'a';
module.exports['b'] = 'b';
Object.defineProperty(module.exports, 'c', {
value: 'c'
});
setTimeout(() => {
console.log('dynamic assign d');
module.exports['d'] = 'd';
}, 1000)
下边这种情况也不支持
// main.mjs
import { test } from './test.cjs';
console.log(test)
// test.cjs
module.exports['te' + 'st'] = 'test';
我们可以排期把前边 a b c 的情况支持掉