【问题标题】:How to import the exported function of a module asynchronously with dynamic imports and call it?如何通过动态导入异步导入模块的导出函数并调用它?
【发布时间】:2018-11-12 15:05:00
【问题描述】:

在 Promise 的异步回调函数中

promise.then(async callbackResultValue => { //here })

我试过了

const browserd = await import('browser-detect');
if (typeof browserd === 'function') { 
    const browserinfo = browserd();
}

得到:

[ts] 无法调用类型缺少调用签名的表达式。 类型“从不”没有兼容的调用签名。

然后我尝试了:

const browserd:Function = await import('browser-detect');

得到:

[ts] 类型 'typeof import("<path-to-npm-module>' 不可赋值 键入“功能”。 “typeof”类型中缺少属性“apply” 导入("<path-to-npm-module>'.

【问题讨论】:

  • 使用这个的目的是什么?
  • @OPV 我当前的用例是有条件地加载一个模块,该模块使用/依赖于所有目标运行时不支持的 API。

标签: typescript es6-promise typescript2.0 dynamic-import


【解决方案1】:

我只是在同样的事情上苦苦挣扎,然后发现返回的 Promise 中的对象可能不是函数本身,而是一个具有名为 default 的属性的对象,其值是您想要的函数。

在我写这篇文章时,我仍然没有完全理解导出的所有细微差别,但这段代码对我有用:

    import('moduleWithADefaultExportOfAFunction')
        .then(theImport => theImport.default());

【讨论】:

    猜你喜欢
    • 2020-03-02
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 2020-09-05
    • 2017-09-28
    • 2017-07-13
    相关资源
    最近更新 更多