reactjslazy-loadingcode-splittingreact-loadable

Dynamic path import for lazy loading of components using react-loadable


I am creating an app using create-react-app and lazy loading the component using react-loadable.

What I want to do is import dynamic paths for the loader object or the Loadable function of react-loadble module.

Code:

const LoadableComponent = path =>
 Loadable({
  loader: () => import(`${path}`),
  loading: Loader,
 })

const Home = LoadableComponent('./../../pages/Home')
const User = LoadableComponent('./../../pages/User')

If I put the path string in the place of the path variable (Ex. import('./pages/Home')) and call the function it works. But when I use it like the code above Loader will load but it will not continue to load the component anymore. Why doesn't it work if I use the variable in import?


Solution

  • Found the answer here

    "For Webpack to handle an import, it needs to be able to at least guess roughly what an import() is meant to be referencing."

    Turns out your path cannot be too anonymous. Guess it is stacked to deep for Webpack to confidently know what I am importing.