patternjavascriptModerate
Webpack code splitting with dynamic imports and magic comments
Viewed 0 times
Webpack 4+
webpack code splittingdynamic importlazy loadingwebpackChunkNameprefetch preload
Problem
A large application ships one monolithic bundle, causing slow initial load. All code is downloaded even for routes the user may never visit.
Solution
Use dynamic import() to create async chunks. Webpack splits these automatically. Use magic comments to control chunk naming and prefetching.
// Route-based splitting
const Dashboard = React.lazy(() =>
import(/ webpackChunkName: "dashboard" / './pages/Dashboard')
);
// Prefetch a chunk when browser is idle
import(/ webpackPrefetch: true / './HeavyModal');
// Preload a chunk needed soon
import(/ webpackPreload: true / './CriticalComponent');
// Group related modules into a named chunk
import(/ webpackChunkName: "charts" / './BarChart');
import(/ webpackChunkName: "charts" / './LineChart');
// Route-based splitting
const Dashboard = React.lazy(() =>
import(/ webpackChunkName: "dashboard" / './pages/Dashboard')
);
// Prefetch a chunk when browser is idle
import(/ webpackPrefetch: true / './HeavyModal');
// Preload a chunk needed soon
import(/ webpackPreload: true / './CriticalComponent');
// Group related modules into a named chunk
import(/ webpackChunkName: "charts" / './BarChart');
import(/ webpackChunkName: "charts" / './LineChart');
Why
Webpack tracks import() calls as split points. Each split point becomes a separate output file. The runtime only fetches chunks when they are actually needed, reducing the initial payload to the minimum required to boot the app.
Gotchas
- webpackPrefetch adds <link rel='prefetch'> — the browser downloads during idle time, good for next navigation
- webpackPreload adds <link rel='preload'> — downloaded in parallel with current chunk, use carefully
- Magic comments are Webpack-specific and stripped by other bundlers; wrap in a try-catch if tooling-agnostic
- Very fine-grained splitting can increase the number of HTTP requests; aim for 30-50 kB chunks
Context
Optimising a Webpack app's initial load time by lazy-loading routes and heavy components
Revisions (0)
No revisions yet.