async-reactor
async-reactor copied to clipboard
Load dynamic node modules
Is it possible to load node modules asynchronously using async-reactor
. The following snippet does not work but I hope explains the use case:
import React from 'react'
import { asyncReactor } from 'async-reactor'
const Component = async arr => (
<div>
{arr.map(obj => {
const Icon = await import(obj.nodeModule)
return (
<div key={obj.title}>
<Icon /> {obj.title}
</div>
)
})}
</div>
)
export default asyncReactor(Component)
obj.nodeModule
is a dynamic string and the import path of a node module, in my case styled-icons
, e.g. obj.nodeModule = styled-icons/boxicons-logos/Github
.
Are you seeing an error? async-reactor
is taking advantage of the import
function but it has no control on it, it's likely your bundler that fails.
Yes, I'm getting
Unhandled Rejection (Error): Cannot find module 'styled-icons/boxicons-logos/Github'
even though the module is definitely installed. Do I need to provide an absolute path or something?
have you tried to remove node_modules and reinstall it?
Yes, I tried that. No change. Since it's a named export, not a default one, I also tried
const { Github } = await import(obj.nodeModule)
const Github = await import(obj.nodeModule).Github
const Github = await import(obj.nodeModule)[`Github`]
but none of those variations had any effect.
What bundler are you using? I can't really tell what's the issue, but it seems to me that the bundler isn't resolving the asset.
If the import() returns a promise, async-reactor will work.
It's a Gatsby project so the bundler is webpack.