I saw today in a project a lazy imports like this:
const AnimatedScore = React.lazy(() => import('../components/AnimatedScore'))
const FireworksCanvas = React.lazy(
() => import('../components/FireworksCanvas'),
)
const Header = React.lazy(() => import('../components/Header'))
const URLForm = React.lazy(() => import('../components/URLForm'))
const LoadingErrorMessages = React.lazy(
() => import('../components/LoadingErrorMessages'),
)
const RadarChartSection = React.lazy(
() => import('../components/RadarChartSection'),
)
const ExceededSentences = React.lazy(
() => import('../components/ExceededSentences'),
)
const Footer = React.lazy(() => import('../components/Footer'))
const SubHeader = React.lazy(() => import('../components/SubHeader'))
After running npm run build
, build time took 3.64
seconds!
So, what did I do to optimize this?
I switched to using the map method:
const [
AnimatedScore,
FireworksCanvas,
Header,
URLForm,
LoadingErrorMessages,
RadarChartSection,
ExceededSentences,
Footer,
SubHeader,
] = [
'AnimatedScore',
'FireworksCanvas',
'Header',
'URLForm',
'LoadingErrorMessages',
'RadarChartSection',
'ExceededSentences',
'Footer',
'SubHeader',
].map((component) => React.lazy(() => import(`../components/${component}.tsx`)))
And after this modification, I got 926ms
. Incredible, isn't it?
But how this this happen behind the scenes?
Explanation
Just for those who may not know, chunks are pieces of your JavaScript code that the bundler (like Vite) splits to optimize loading. Instead of loading a huge file with all your code at once, the browser loads only the necessary chunks when they are needed.
Imagine your app has three pages: Home, About, and Contact. If all the JavaScript was in one big file (bundle.js
), the user would have to download everything - even the code for pages they never visit!
Instead, a bundler splits your code like this:
-
main.js
→ Contains shared code used across the entire app. -
home-[hash].js
→ Loads only when the user visits the Home page. -
about-[hash].js
→ Loads only when the user visits the About page.
Bundlers like Vite and Webpack typically add a unique hash (e.g., home-abc123.js
) to filenames for better caching and cache invalidation.
And now when we know what are chunks let's see why the map methods optimizes build time.
By using map for dynamic imports, the bundler can group and optimize chunks more efficiently instead of handling each import() separately.
This means that the bundler(like Vite) can process the map in one go, creating all the required chunks more efficiently.
Summary
In short, switching from single-line lazy imports to using a map for dynamic imports optimizes the build process by:
- Reducing redundant operations in the bundling process
- Allowing better chunk creation and grouping
- Enabling better parallelization of the chunk creation process
- Optimizing chunk reuse
Code in action?
Sure, check it here (DevToPostAnalyzer.tsx) on GitHub.
Did you know about this approach to lazy imports? Share your thoughts in the comments below! 💬
Top comments (8)
This is interesting; how is it determined to only import those components and create chunks for them? The pattern where the import has a variable in it usually makes a chunk for each possible file as it can't deterministically calculate what could be supplied. I guess that's ok if you will always lazy import everything in components, but if some were static, then it would generate some unnecessary stuff, wouldn't it?
Great question! Normally, when using
import(\../components/${component}.tsx
) with a variable, bundlers have to assume that any file in../components/
could be a match, which can lead to unnecessary chunks.However, in this case, the list of components is hardcoded inside the array, so the bundler can statically analyze all possible imports. This means it knows exactly which files will be loaded and doesn’t have to create chunks for undefined or unexpected files.
Regarding your last point - Yes, if some components were also statically imported somewhere else, this could make redundant chunks.
Interesting!
Thanks for feedback! Glad it was helpful :)
Definitely trying this, thanks for sharing
Glad it was helpful :)
If you want to see it in action feel free to check repository.
Or specifically, this file: DevToPostAnalyzer.tsx.
This syntax is exactly what I have been looking for. Absolutely will try this, thank you for sharing mate.
You're welcome!
If you want to see it in action feel free to check repository.
Or specifically, this file: DevToPostAnalyzer.tsx.