Chapter 8: Code Splitting
Chapter 8 of 12
Chapter 8: Code Splitting
8.1 Dynamic Imports
Code splitting divides your bundle into smaller chunks that load on demand.
// Dynamic import
const LazyComponent = React.lazy(() => import('./LazyComponent'));
// Webpack automatically creates separate chunk
// chunk-vendors.js (vendor code)
// chunk-common.js (shared code)
// chunk-app.js (app code)
// Webpack configuration
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\/]node_modules[\/]/,
name: 'vendors',
priority: 10
},
common: {
minChunks: 2,
priority: 5,
reuseExistingChunk: true
}
}
}
}
8.2 Route-Based Splitting
// Split by routes
const Home = React.lazy(() => import('./pages/Home'));
const About = React.lazy(() => import('./pages/About'));
// Each route becomes a separate chunk