我两天前看了BUN的文件.我很难理解这个:
我在谷歌上搜索了一下,发现很多人也提到了这一点,但没有人解释.以下是一些参考:
- How to dynamically load ESM in CJS个
- CommonJS (cjs) and Modules (esm): Import compatibility个
- Interoperability with CommonJS个
在我看来,ES模块的加载与静态导入是同步的.例如:
// exporter.mjs
console.log("exporter");
// importer.mjs
import "exporter.mjs"
console.log("importer");
使用此命令node importer.mjs
.如果exporter.js
的加载是异步的,则输出将首先是"Importer"打印,然后是"Exporter"打印.而结果是"出口商"首先打印,"进口商"紧随其后.
enter image description here个
这证明了ES模块的加载与静态导入是同步的,在这种情况下,我们可以在CommonJS模块中导入ES模块.虽然我上面提到的文章都说"我们不能在CommonJS模块中导入ES模块,但我们必须使用the dynamic import function",NodeJS的文档也是如此.但是,我们可以在BUN的CommonJS模块中导入ES模块.这是一个例子:
// exporter.mjs
export let number = 10;
// importer.cjs
const { number } = require("./exporter.mjs");
console.log(number);
使用此命令bun importer.cjs
.我们可以像这样得到输出.
enter image description here个
我真的很困惑.