Reputation: 36004
I'd like to export a different package from a custom module based on an expression
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
However, when i import this file later i receive a pending promise
import Sentry from 'config/sentry'
console.log(Sentry) // -> promise pending
Is it possible to default export the dynamically imported module at the top level?
I ended up going with require instead of dynamic imports, as supported by webpack globals setup on my system
const Sentry = __CLIENT__ ? require('@sentry/browser') : require('@sentry/node')
Upvotes: 2
Views: 2994
Reputation: 5566
Async functions always return a promise. That's by definition. Since dynamic imports also return promises (and are async), you can't export them, since exports have to be at the top level of a script. The best you can do is export the promise and include a .then
handler in whichever script imports it; since you're returning mod
from your async function, that will be passed to the .then
handler's parameter for you to use there.
Upvotes: 3