我的项目完全是用 CommonJS 模块编写的,我无法更改它。我正在尝试使用一个 ESM 库。该库是 Got 库 (https://github.com/sindresorhus/got)。
这是我的代码
const request = require('request');
const Promise = require('bluebird');
// require('./wrapped-got');
var wrappedgot = null;
function HTTPRequestV2(hostURL, defaultOptions) {
this.hostUrl = hostURL;
this.requestWrapper = request.defaults(defaultOptions);
}
HTTPRequestV2.prototype.init = async function(){
wrappedgot = await import('got');
/*return import('got')
.then(({default: theDefault}) => {
wrappedgot= theDefault;
console.log(theDefault);
});
console.log(wrappedgot);*/
};
但是在运行此命令时,我在 wrappedgot = wait import('got'); 行 上收到错误 Not Supported
我尝试按照问题页面中的建议使用动态导入功能的解决方法,但由于上述错误而失败 https://github.com/sindresorhus/got/issues/1789
甚至尝试运行他们的示例代码,但也失败并出现相同的错误 https://gist.github.com/szmarczak/0f2b70b2a1ed52a56a6d391ac02d094d
------更新-----
我使用的是 Node 版本 12.14.1,它支持异步和等待。 我读过 SO,它已在 Node 版本 10 中使用
得到的库版本是13.0.0
我很确定导入必须在全局范围内,并且您尝试在函数内部使用
import
。您必须将 import
移到该函数之外才能消除错误。作为解决方案, import
'got' 位于顶部,并包含这些要求并将其分配给一个变量,然后当函数 HTTPRequestV2.prototype.init
运行时,您应该将 'wrappedgot' 设置为保存 'got' 导入的任何变量。我希望这有帮助。
<------------------ General improvements to this code ------------------>
这也是不相关的,但你在顶部命名了一个变量“Promise”,这确实应该避免,因为 Promise 是 JavaScript 中的构造函数,并且用于其他用途,通过使用它的名称可能会导致其他用途实际上承诺会抛出错误。
我还建议在当今时代不要使用“var”,因为它是 JavaScript 的旧版本,可能会导致您可能意想不到的错误,除非您知道自己在做什么。
我还建议使用
import
而不是要求保持最新的实现。