Next.js: How to use Template literals with dynamic import?

Created on 3 Apr 2018  ·  10Comments  ·  Source: vercel/next.js

How to use Template literals with dynamic import?
const Component = dynamic(import(/components/${kindOf}))
In console i have error

Module build failed: TypeError ... Cannot read property '0' of undefined

Most helpful comment

Fixed in #4639

All 10 comments

You can't do truly dynamic imports. Webpack can't predict the outcome and prebundle.

@timneutkens This is not true. Webpack can handle dynamic imports where part of the path is static. From the docs:

Every module that could potentially be requested on an import() call is included. For example, import(./locale/${language}.json) will cause every .json file in the ./locale directory to be bundled into the new chunk. At run time, when the variable language has been computed, any file like english.json or german.json will be available for consumption.

This error is specifically a deficiency in next/babel, where only static strings are handled but not template literals (which are of a different AST node type). Another unrelated aspect is that all import()s are transformed, even those not wrapped in a call to dynamic() – which is problematic for non-component dynamic imports.

Lets re-open the issue then.

Would really love to see this get support added.

This error is specifically a deficiency in next/babel

@herrstucki You mean because of the handle-import babel plugin?

@herrstucki is there any solution for this problem?

I'd just like to add that this is especially useful when trying to internationalize an app since it allows us to split up imports from moment and react-intl.

For reference: https://github.com/yahoo/react-intl/issues/777#issuecomment-270134176

Ran into this today while building out a portfolio page on a website. Just thought I'd throw in my experience for more context 😄

I have a pages/portfolio/index.js page that renders out a bunch of thumbnails. These thumbnails use next/link with a config like:

<Link href={`/portfolio/item?id=${id}`} as={`/portfolio/${id}`} prefetch>

When clicked, the component at pages/portfolio/item.js renders. This component's getInitialProps function looks like:

static async getInitialProps({ query }) {
    const data = await import(`../../portfolio/${query.id}.json`)
    return { data }
  }

But unfortunately I'm getting the same error as above:

Module build failed: TypeError ... Cannot read property '0' of undefined

Attempting to find a workaround for now. I will update here if I find anything 👍

Fixed in #4639

Was this page helpful?
0 / 5 - 0 ratings

Related issues

olifante picture olifante  ·  3Comments

pie6k picture pie6k  ·  3Comments

jesselee34 picture jesselee34  ·  3Comments

knipferrc picture knipferrc  ·  3Comments

kenji4569 picture kenji4569  ·  3Comments