Next.js: Dynamic imports with dynamic filenames

Created on 21 May 2017  路  4Comments  路  Source: vercel/next.js

I am working from next version 3.0.0-beta5. I have setup a demo application here: https://github.com/kylesuss/next-dynamic-issue

What I would like to do is to dynamically import components, but the filename to dynamically import will not be constant. For example:

loadDynamicComponent = (event) => {
  const componentName = event.target.dataset.component;
  const DynamicComponent = dynamic(import(`../components/${componentName}`))
  this.setState({ dynamicComponent: <DynamicComponent />  })
}

https://github.com/kylesuss/next-dynamic-issue/blob/eb999951ed8e00134b192ea44b7f15b81f382706/pages/index.js#L10-L14

Is such a thing possible? Currently, I get an error:

TypeError: Cannot read property 'call' of undefined

screen shot 2017-05-21 at 2 31 43 pm

When I change the code to hardcode the component path, all is well:

loadDynamicComponent = (event) => {
  const DynamicComponent = dynamic(import(`../components/dynamic`))
  this.setState({ dynamicComponent: <DynamicComponent />  })
}

This seems to defeat my purpose for dynamic components. I understand there are concerns with module loading & server side rendering, but what's the best way to achieve something like this? Am I missing the point? Is this a bug / not yet implemented?

Thanks.

Most helpful comment

I see. Thanks for the link! Makes sense.

All 4 comments

No you can't do that.
But this how you can achieve the same thing.
See: https://github.com/zeit-day/nextjs-dynamic-comp-chat/blob/master/pages/index.js

There's a similar issue in this issue list. Just search for that for more info.

I see. Thanks for the link! Makes sense.

@arunoda any examples of how to just dynamically import some lib as a promise? Having to jump through some crazy hoops (wrap every lib in a component?). Using regular webpack dynamic imports doesn't appear to work.

Was this page helpful?
0 / 5 - 0 ratings