SkillByAIOpen interactive version →

Lesson 9 / 25

Tree-shaking and code splitting

Cut bundle size with tree-shaking and code splitting using dynamic imports and splitChunks vendor extraction.

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?

  • Shaking the dependency tree to find bugs.
  • Removing unused code from the bundle.
  • Reordering imports in files.
  • Renaming files to shorter names.
Answer

Removing unused code from the bundle. — Tree-shaking eliminates unused exports in production builds, reducing bundle size by removing dead code.