Compressing JavaScript Bundles with Gzip
Learn how gzip compression affects JavaScript bundle sizes. See typical compression ratios for JS and strategies to maximize savings.
Detailed Explanation
JavaScript Bundle Compression
JavaScript is one of the most compressible asset types on the web. Gzip can typically reduce JS bundle sizes by 65–75%, making compression essential for performance.
Why JavaScript Compresses Well
JavaScript contains many repeated patterns that DEFLATE exploits:
- Keywords:
function,const,return,import,exportappear hundreds of times - Identifiers: Variable names, function names, property accesses
- Syntax: Brackets, semicolons, parentheses, dots
- String literals: Repeated strings in templates, error messages
Minification + Gzip: The Winning Combination
| Step | Size (example React app) |
|---|---|
| Original source | 500 KB |
| After minification (Terser) | 180 KB (64% reduction) |
| After gzip (level 6) | 55 KB (69% further reduction) |
| Total reduction | 89% |
Minification removes comments, whitespace, and renames variables. Gzip then compresses the remaining patterns. Both steps complement each other — minified code still has plenty of repetition for gzip to exploit.
Tree Shaking Before Compression
Modern bundlers (webpack, Rollup, esbuild) perform tree shaking to remove unused code. This reduces the input size before compression, yielding smaller outputs:
Full lodash: 71 KB minified → 25 KB gzipped
Tree-shaken: 12 KB minified → 4 KB gzipped
Source Maps
Remember that source maps (.js.map) are also highly compressible (80–90% reduction) but should only be served to developer tools, not to all users. Configure your server to serve them with appropriate access controls.
Use Case
Frontend developers optimizing bundle sizes for faster page loads. Understanding JS compression helps set realistic performance budgets and make informed decisions about code splitting.