导出动态导入

时间:2019-06-17 17:04:35

标签: javascript

我想从基于表达式的自定义模块中导出另一个包

const settings = {}

const init = (sentry) => {
  sentry.init(settings)
  return sentry
}

const pkg = async () => {
  let mod

  if (__CLIENT__) {
    mod =  await import('@sentry/browser').then(init)
  } else {
    mod = await import('@sentry/node').then(init)
  }
  return mod
}

const Sentry = pkg()

console.log({ Sentry })

export default Sentry

但是,当我稍后导入此文件时,我会收到未决的诺言

import Sentry from 'config/sentry'
console.log(Sentry) // -> promise pending 

是否可以默认在顶层导出动态导入的模块?

更新

我最终选择了require而不是动态导入,因为系统上的webpack全局设置支持

const Sentry = __CLIENT__ ? require('@sentry/browser') : require('@sentry/node')

1 个答案:

答案 0 :(得分:1)

异步函数总是返回承诺。根据定义。由于动态导入还会返回承诺(并且是异步的),因此您不能导出承诺,因为导出必须位于脚本的顶层。您所能做的最好的事情就是导出承诺,并在导入脚本的任何脚本中都包含一个.then处理程序。由于您要从异步函数中返回mod,因此该参数将传递到.then处理程序的参数中供您使用。