Lesson 9 / 25
Tree-shaking and code splitting
Remove unused code and split bundles for efficiency.
Eliminating dead code
Tree-shaking removes unused exports in production mode. It relies on ES6 module static structure to identify what's imported. Imports you don't use are eliminated. Code splitting divides bundles into chunks that load on demand, reducing initial load time. Use dynamic imports to trigger code splitting.
Code splitting example
Use dynamic imports to create separate chunks.
// Load module only when needed
const handleClick = async () => {
const { heavyModule } = await import('./heavy.js');
heavyModule();
};
button.addEventListener('click', handleClick);
Output:
Creates: main.js, heavy.HASH.js (loaded on click)
Optimize split chunks
Configure splitChunks to extract vendor dependencies into separate bundles. This allows browser caching of vendor code across page updates. Cache vendor bundles longer since they change less frequently.
Quick check
Quick check: What is tree-shaking?
- Removing unused code from the bundle.
- Shaking the dependency tree to find bugs.
- Reordering imports in files.
Answer
Removing unused code from the bundle. — Tree-shaking eliminates unused exports in production builds, reducing bundle size by removing dead code.