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
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?
@vjpr yes, this line fails with a template literal: https://github.com/zeit/next.js/blob/4881cd346b8155314c02a6996538fb48d324111d/server/build/babel/plugins/handle-import.js#L57
@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
Most helpful comment
Fixed in #4639