【发布时间】:2021-09-22 22:54:00
【问题描述】:
我正在尝试解决我需要将pure ESM package 导入非模块的事实。我无法改变关于the script 的事实。
我尝试使用的解决方法是import() 函数(“dynamic import”)。这将返回一个 Promise 而不是实际的模块。我不能使用await,因为我不在模块中,所以我使用.then()。
纯 ESM 包 (unist-util-visit) 用于我的脚本导出的函数中,然后在另一个脚本中使用。所以导入链去:
importer.js 导入 imported.js 导入 unist-util-visit
所以问题是我从imported.js 中的.then() 函数中导出的任何内容都不会出现在importer.js 中。
这甚至不是时间问题。我使用EventEmitter 让importer.js 等到imported.js 的.then() 执行完毕:
imported.js:
const EventEmitter = require('events');
module.exports.emitter = new EventEmitter();
module.exports.outsideFxn = function () {
console.log('hello');
}
import('unist-util-visit').then((unistUtilVisit) => {
module.exports.fxn = function() {
console.log(`unistUtilVisit: ${typeof unistUtilVisit}`);
}
module.exports.emitter.emit('ready');
});
importer.js:
import('./imported.js').then((imported) => {
console.log("In importer.js's .then():");
console.log(' fxn:', imported.fxn);
console.log(' outsideFxn:', imported.outsideFxn);
imported.emitter.on('ready', () => {
console.log("After imported.js is done:")
console.log(' fxn:', imported.fxn);
});
});
当我执行它时,这是输出:
$ node importer.js
In importer.js's .then():
fxn: undefined
outsideFxn: [Function (anonymous)]
After imported.js is done:
fxn: undefined
我错过了什么?为什么.then() 函数中没有定义导出?如何导出我的函数?
【问题讨论】:
标签: javascript node.js es6-promise es6-modules