Search code examples
reactjses6-promisecode-splitting

Adding custom function and promise to React.lazy causing error


I'm using React.lazy to do route-based code splitting. Additionally, I'm adding a minimum delay as described here. The purpose of the delay is to show a load animation for a minimum amount of time on each lazy load.

Everything works fine when I have each route setup as below:

const ExampleComponent = React.lazy(() => 
  Promise.all([
    import('./ExampleRoute'),
    new Promise(resolve => setTimeout(resolve, MIN_DELAY))
  ])
  .then(([moduleExports]) => moduleExports));

However, when I try to move my promise to a function everything breaks:

const lazyPromise = (route) =>
  Promise.all([
    import(route),
    new Promise(resolve => setTimeout(resolve, MIN_DELAY))
  ])
  .then(([moduleExports]) => moduleExports);

const ExampleComponent = React.lazy(() => lazyPromise('./ExampleRoute'));

The error I'm getting: Cannot find module './ExampleRoute'

What am I missing here? Any help will be appreciated. Thanks!


Solution

  • I'm answering my own question to help anyone who comes across this in the future. This answer elaborates on the comments from estus and Prakash Sharma above.

    webpack must be statically buildable, and does not support the use of any path variables, including query strings. If a value is not available until runtime, webpack will not be able to see it.

    More information about how webpack handles code-splitting can be found here.