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
By using a map (or reduce to generate lazy imports dynamically), you are providing the bundler with an efficient list of dependencies upfront. Instead of dealing with separate import() statements for each component, you are defining all components at once.
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
Did you know about this approach to lazy imports? Share your thoughts in the comments below! 💬
Top comments (0)