In previous posts, I’ve shown the basic amount of work to lazy-load a component. In this post, we’ll dive further into a more realistic example of dynamically lazy-loading components when bundling your application with webpack.
In my last example we looked at dynamically importing components like this:
const LazyComponent = lazy(() => import('./components/' + myVarHoldingTheComponentName);
The above call fails when using webpack to bundle your application. So what can we do?
We need to understand why the above is failing before being able to apply a fix. So the error message will shine some light on the underlying issue:
Error: Cannot find module ...
Unfortunately, this is quite an unhelpful error message. This doesn’t help very much, and as it turns out, the issue has to do with how webpack chunks files and not so much about not being able to read the path of the lazy-loaded component. I’ll circle back to this error given time but for the time being let’s move on.
In order for dynamically loaded React components using a webpack bundle, you need to separate the path, module name and extension so that webpack can statically bind everything in the folder that you are going to lazy-load components from. For example:
const LazyComponent = lazy(() => import('components/' + moduleNameInVar + '.js'));
This means that all components in the components folder will be chunked by webpack and ready for lazy loading. It’s important to note that this is required if you build your app using create-react-app.