2

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!

Don Brody
  • 1,689
  • 2
  • 18
  • 30
  • 1
    Webpack wasn't configured for code splitting. It doesn't know that `ExampleRoute` needs to be included into the bundle. See https://webpack.js.org/guides/code-splitting/#dynamic-imports – Estus Flask Jan 30 '19 at 19:36
  • 2
    You cannot pass a variable to `import`. The module bundler can't figure out which module to include while bundling because that variable value is only available at runtime. – Prakash Sharma Jan 30 '19 at 19:38
  • Ahh I see. That makes sense. Thanks to you both! – Don Brody Jan 30 '19 at 19:41

1 Answers1

0

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.

Don Brody
  • 1,689
  • 2
  • 18
  • 30