ESModule加载是否为异步?CommonJS与ESM互操作疑惑
CommonJS与ES Modules同步/异步特性及Bun兼容性疑问
两天前查阅Bun文档时,对以下描述感到困惑:
"CommonJS与ES Modules最大的区别在于CommonJS模块是同步的,而ES Modules是异步的。"
搜索后发现不少资料都提及这一点,但没有详细解释,相关参考包括:
- 《How to dynamically load ESM in CJS》
- 《CommonJS (cjs) and Modules (esm): Import compatibility》
- Node.js官方文档《Interoperability with CommonJS》
我认为静态import时ES模块的加载是同步的,做了如下测试:
// exporter.mjs console.log("exporter");
// importer.mjs import "exporter.mjs" console.log("importer");
执行命令 node importer.mjs,若ES模块加载是异步的,输出应该先显示"importer"再显示"exporter",但实际结果是先输出"exporter",再输出"importer"。
这似乎证明静态import时ES模块加载是同步的,那理论上CommonJS模块应该可以直接导入ES模块,但上述资料及Node.js官方文档都明确表示CommonJS无法用require()导入ES模块,必须使用动态import()函数。
但在Bun中却能实现这种导入,示例如下:
// exporter.mjs export let number = 10;
// importer.cjs const { number } = require("./exporter.mjs"); console.log(number);
执行命令 bun importer.cjs 可以正常输出10,这让我十分困惑。
内容的提问来源于stack exchange,提问作者Devin Johw
相关产品推荐
相关产品推荐

