Pre-Compression in Build Pipelines — .gz and .br Files
Learn how to pre-compress assets at build time for maximum compression without runtime cost. Configure webpack, Vite, and nginx for pre-compressed serving.
Optimization
Detailed Explanation
Pre-Compression: Build-Time Compression
Pre-compression means generating .gz and .br compressed versions of static assets during the build process rather than compressing on every HTTP request.
Why Pre-Compress?
| Approach | Compression Level | CPU Cost | Latency Impact |
|---|---|---|---|
| On-the-fly (level 6) | Moderate | Every request | Adds 1–10ms |
| Pre-compressed (level 9/11) | Maximum | Build time only | Zero |
Pre-compression gives you maximum compression with zero runtime cost.
Webpack Configuration
// webpack.config.js
const CompressionPlugin = require('compression-webpack-plugin');
module.exports = {
plugins: [
// Gzip
new CompressionPlugin({
filename: '[path][base].gz',
algorithm: 'gzip',
test: /\.(js|css|html|svg|json)$/,
threshold: 1024,
minRatio: 0.8,
}),
// Brotli
new CompressionPlugin({
filename: '[path][base].br',
algorithm: 'brotliCompress',
test: /\.(js|css|html|svg|json)$/,
compressionOptions: { level: 11 },
threshold: 1024,
minRatio: 0.8,
}),
],
};
Vite Configuration
// vite.config.js
import viteCompression from 'vite-plugin-compression';
export default {
plugins: [
viteCompression({ algorithm: 'gzip' }),
viteCompression({ algorithm: 'brotliCompress' }),
],
};
Nginx Pre-Compressed Serving
# Serve pre-compressed files when available
gzip_static on; # Serves .gz files
brotli_static on; # Serves .br files (requires ngx_brotli)
When a request comes in for bundle.js, nginx checks for bundle.js.br (if client supports Brotli) or bundle.js.gz (if client supports gzip) and serves the pre-compressed version directly.
Build Output Example
dist/
bundle.js (450 KB) — original
bundle.js.gz ( 95 KB) — gzip level 9
bundle.js.br ( 78 KB) — brotli level 11
styles.css (120 KB)
styles.css.gz ( 18 KB)
styles.css.br ( 14 KB)
Use Case
Build pipeline optimization for production deployments. Essential for teams that want maximum compression ratios without paying a CPU cost on every request in production.