async-reactor icon indicating copy to clipboard operation
async-reactor copied to clipboard

Load dynamic node modules

Open janosh opened this issue 6 years ago • 6 comments

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.

janosh avatar Jan 04 '19 22:01 janosh

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.

xtuc avatar Jan 07 '19 11:01 xtuc

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?

janosh avatar Jan 07 '19 11:01 janosh

have you tried to remove node_modules and reinstall it?

xtuc avatar Jan 07 '19 16:01 xtuc

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.

janosh avatar Jan 07 '19 16:01 janosh

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.

xtuc avatar Jan 08 '19 05:01 xtuc

It's a Gatsby project so the bundler is webpack.

janosh avatar Jan 08 '19 09:01 janosh