Bundle Optimization
Reduce JavaScript bundle size through tree shaking, dependency analysis, and build configuration tuning.
You are an expert in JavaScript bundle size optimization for optimizing application performance.
## Key Points
- **Parse/compile cost:** ~1ms per 10KB of minified JS on mid-range mobile devices. A 500KB bundle can cost 50ms+ just to parse.
- **Tree shaking:** Dead-code elimination that removes unused exports at build time. Requires ES module syntax (`import`/`export`).
- **Bundle budget:** A hard limit on total JS size. Recommended baseline: < 170KB compressed for initial load (per Google).
- **Dependency weight:** A single library can dominate the bundle. `moment.js` (~300KB) vs `date-fns` (~15KB tree-shaken) is a classic example.
- **Build-time:** Use `webpack-bundle-analyzer` or `source-map-explorer` to visualize chunk composition after every build.
- **CI enforcement:** Add `bundlesize` or `size-limit` to the CI pipeline with configured thresholds.
- **Runtime:** Track Time to Interactive (TTI) and Total Blocking Time (TBT) as proxies for JS cost.
- Audit dependencies quarterly with `npx depcheck` and remove unused packages.
- Prefer libraries that publish ES modules and support tree shaking (check the `module` or `exports` field in `package.json`).
- Enable gzip or Brotli compression on the server — Brotli typically yields 15-20% smaller payloads than gzip.
- Importing from a package index barrel file (`import { x } from 'lib'`) when the library does not support tree shaking, pulling in the entire package.
- Forgetting to set `sideEffects: false` in your own library's `package.json`, which prevents bundlers from tree-shaking unused modules.
## Quick Example
```javascript
import moment from 'moment'; // 300KB+
const formatted = moment().format('YYYY-MM-DD');
```
```javascript
import { format } from 'date-fns'; // ~3KB for this function
const formatted = format(new Date(), 'yyyy-MM-dd');
```skilldb get performance-optimization-skills/Bundle OptimizationFull skill: 121 linesBundle Optimization — Performance Optimization
You are an expert in JavaScript bundle size optimization for optimizing application performance.
Core Philosophy
Overview
JavaScript bundle size is one of the largest contributors to slow page loads. Every kilobyte of JS must be downloaded, parsed, compiled, and executed — each step adding latency. Bundle optimization focuses on shipping only the code users actually need, in the most compact form possible.
Core Concepts
- Parse/compile cost: ~1ms per 10KB of minified JS on mid-range mobile devices. A 500KB bundle can cost 50ms+ just to parse.
- Tree shaking: Dead-code elimination that removes unused exports at build time. Requires ES module syntax (
import/export). - Bundle budget: A hard limit on total JS size. Recommended baseline: < 170KB compressed for initial load (per Google).
- Dependency weight: A single library can dominate the bundle.
moment.js(~300KB) vsdate-fns(~15KB tree-shaken) is a classic example.
Implementation Patterns
Analyze the Bundle
# Webpack
npx webpack-bundle-analyzer dist/stats.json
# Vite / Rollup
npx rollup-plugin-visualizer
# Generic size check
npx bundlephobia <package-name>
Replace Heavy Dependencies
Before:
import moment from 'moment'; // 300KB+
const formatted = moment().format('YYYY-MM-DD');
After:
import { format } from 'date-fns'; // ~3KB for this function
const formatted = format(new Date(), 'yyyy-MM-dd');
Enable Tree Shaking via Named Imports
Before:
import _ from 'lodash'; // imports entire library (~70KB)
const result = _.get(obj, 'a.b.c');
After:
import get from 'lodash/get'; // ~1KB
const result = get(obj, 'a.b.c');
Configure Minification and Compression
// vite.config.js
export default {
build: {
minify: 'terser',
terserOptions: {
compress: { drop_console: true, passes: 2 },
},
rollupOptions: {
output: { manualChunks: { vendor: ['react', 'react-dom'] } },
},
},
};
Measurement & Monitoring
- Build-time: Use
webpack-bundle-analyzerorsource-map-explorerto visualize chunk composition after every build. - CI enforcement: Add
bundlesizeorsize-limitto the CI pipeline with configured thresholds. - Runtime: Track Time to Interactive (TTI) and Total Blocking Time (TBT) as proxies for JS cost.
// package.json — size-limit config
{
"size-limit": [
{ "path": "dist/index.js", "limit": "50 KB" },
{ "path": "dist/vendor.js", "limit": "120 KB" }
]
}
Best Practices
- Audit dependencies quarterly with
npx depcheckand remove unused packages. - Prefer libraries that publish ES modules and support tree shaking (check the
moduleorexportsfield inpackage.json). - Enable gzip or Brotli compression on the server — Brotli typically yields 15-20% smaller payloads than gzip.
Common Pitfalls
- Importing from a package index barrel file (
import { x } from 'lib') when the library does not support tree shaking, pulling in the entire package. - Forgetting to set
sideEffects: falsein your own library'spackage.json, which prevents bundlers from tree-shaking unused modules.
Anti-Patterns
Over-engineering for hypothetical scale. Building for millions of users when you have hundreds adds complexity without value. Solve today's problems first.
Ignoring the existing ecosystem. Reinventing functionality that mature libraries already provide well wastes time and introduces unnecessary risk.
Premature abstraction. Creating elaborate frameworks and utilities before you have enough concrete cases to know what the abstraction should look like produces the wrong abstraction.
Neglecting error handling at boundaries. Internal code can trust its inputs, but system boundaries (user input, APIs, file I/O) require defensive validation.
Skipping documentation for obvious code. What is obvious to you today will not be obvious to your colleague next month or to you next year.
Install this skill directly: skilldb add performance-optimization-skills
Related Skills
Caching Strategies
Design effective browser and CDN caching strategies using Cache-Control headers, ETags, service workers, and edge caching.
Code Splitting
Reduce initial load time with route-based and component-level code splitting using dynamic imports and framework-specific patterns.
Core Web Vitals
Optimize Largest Contentful Paint, First Input Delay, and Cumulative Layout Shift for better user experience and search rankings.
Database Query Optimization
Optimize database queries through indexing, query planning, N+1 elimination, connection pooling, and schema design.
Image Optimization
Optimize image delivery with modern formats, responsive sizing, lazy loading, and CDN-based transformations.
Memory Management
Prevent memory leaks and optimize memory usage through proper cleanup patterns, profiling, and garbage collection awareness.