### Install Dependencies and Start Development Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/__tests__/specials/tanstack/README.md Install project dependencies and start the development server. The app will rebuild assets on file changes. ```sh pnpm install pnpm dev ``` -------------------------------- ### Install Dependencies, Build, and Preview Project Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/example/README.md Run these commands to install dependencies, build static resources, and start a local server to preview the results. ```bash $ yarn // install dependices ``` ```bash $ yarn build // packing static resources ``` ```bash $ yarn preview // start a local server to preivew the result. ``` -------------------------------- ### Start New TanStack Project Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/__tests__/specials/tanstack/README.md Use this command to initialize a new project based on the TanStack Start basic example. ```sh npx gitpick TanStack/router/tree/main/examples/react/start-basic start-basic ``` -------------------------------- ### Filename Patterns Example Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Demonstrates that filename patterns remain unchanged and continue to work as expected in v2.x. ```javascript compression({ filename: '[path][base].gz', algorithms: ['gzip'] }) ``` -------------------------------- ### Install vite-plugin-compression2 with pnpm Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Install the plugin as a development dependency using pnpm. ```bash $ pnpm add vite-plugin-compression2 -D ``` -------------------------------- ### Install vite-plugin-compression2 with npm Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Install the plugin as a development dependency using npm. ```bash $ npm install vite-plugin-compression2 -D ``` -------------------------------- ### Serve compressed files locally with npx serve Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md After building your project, use `npx serve dist` to serve the compressed files locally. This command starts a static server that can serve pre-compressed assets. ```bash # Build your project npm run build # Serve with a static server that supports pre-compressed files npx serve dist ``` -------------------------------- ### Install vite-plugin-compression2 with Yarn Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Install the plugin as a development dependency using Yarn. ```bash $ yarn add vite-plugin-compression2 -D ``` -------------------------------- ### Nginx configuration for static compression in Docker Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md This Dockerfile example demonstrates a build stage using Node.js to build the project and then serves the static assets using Nginx. It assumes that vite-plugin-compression has already created the compressed files. ```dockerfile # Build stage FROM node:20-alpine AS builder WORKDIR /app COPY package*.json ./ RUN npm ci COPY . . RUN npm run build # Serve stage (example assumes Nginx is configured to serve static files) # FROM nginx:alpine # COPY --from=builder /app/dist /usr/share/nginx/html # EXPOSE 80 # CMD ["nginx", "-g", "daemon off;"] ``` -------------------------------- ### Basic Vite Plugin Compression Setup Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Integrate the compression plugin into your Vite configuration for basic asset compression. ```javascript import { defineConfig } from 'vite' import { compression } from 'vite-plugin-compression2' export default defineConfig({ plugins: [ // ...your plugins compression() ] }) ``` -------------------------------- ### Update Package Installation Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Install the latest version of vite-plugin-compression2 using npm. ```bash npm install vite-plugin-compression2@latest -D ``` -------------------------------- ### AWS CloudFront Configuration for Compression Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Example AWS CloudFront configuration settings for enabling compression. Ensure 'Compress' is set to true. ```json { "Compress": true, "ViewerProtocolPolicy": "redirect-to-https", "CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6" } ``` -------------------------------- ### Configure compression with a size threshold Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Use the `threshold` option to compress only files larger than a specified size in bytes. This example uses gzip. ```typescript compression({ threshold: 1024, // Only compress files larger than 1KB algorithms: ['gzip'] }) ``` -------------------------------- ### Delete original assets after compression Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Set `deleteOriginalAssets` to `true` to remove the original uncompressed files after successful compression. This example uses gzip. ```typescript compression({ algorithms: ['gzip'], deleteOriginalAssets: true }) ``` -------------------------------- ### Configuration Update: With Options Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Update configurations with specific options, moving from `algorithm` and `compressionOptions` in v1.x to `algorithms` with `defineAlgorithm` in v2.x. ```javascript // Old compression({ algorithm: 'gzip', compressionOptions: { level: 6 } }) // New compression({ algorithms: [defineAlgorithm('gzip', { level: 6 })] }) ``` -------------------------------- ### Build for Production Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/__tests__/specials/tanstack/README.md Compile the application for production deployment. ```sh pnpm build ``` -------------------------------- ### Build and Inspect Response Headers Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt Build the project and inspect response headers to verify compression. Ensure your server or CDN is configured to serve compressed assets. ```bash npm run build npx serve dist curl -I -H "Accept-Encoding: gzip" http://localhost:3000/assets/main.js # Expected response header: Content-Encoding: gzip curl -I -H "Accept-Encoding: br" http://localhost:3000/assets/main.js # Expected response header: Content-Encoding: br ``` -------------------------------- ### Build Script for Post-Build Compression Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Configure npm scripts to first build the project and then run a separate compression step using Node.js. This allows for compression as a distinct post-build process. ```json { "scripts": { "build": "vite build", "compress": "node compress.js", "build:prod": "npm run build && npm run compress" } } ``` -------------------------------- ### Custom Gzip Level Migration Pattern Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Illustrates the migration of custom gzip compression level settings from v1.x's `algorithm` and `compressionOptions` to v2.x's `algorithms` with `defineAlgorithm`. ```javascript // v1.x compression({ algorithm: 'gzip', compressionOptions: { level: 6 } }) // v2.x compression({ algorithms: [defineAlgorithm('gzip', { level: 6 })] }) ``` -------------------------------- ### Configuration Update: Simple Case Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Migrate a simple algorithm configuration from v1.x to v2.x, changing `algorithm` to `algorithms`. ```javascript // Old compression({ algorithm: 'gzip' }) // New compression({ algorithms: ['gzip'] // or [defineAlgorithm('gzip')] }) ``` -------------------------------- ### Brotli Compression Migration Pattern Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Demonstrates the migration of brotli compression configuration, including specific parameters, from v1.x to v2.x using `defineAlgorithm`. ```javascript // v1.x compression({ algorithm: 'brotliCompress', compressionOptions: { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11 } } }) // v2.x compression({ algorithms: [defineAlgorithm('brotliCompress', { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11 } })] }) ``` -------------------------------- ### Select Compression Levels Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Configure different gzip and brotli compression levels for development (faster builds, lower compression) and production (slower builds, better compression). Use maximum compression for production and recommended levels for development. ```javascript compression({ algorithms: [ // Development: faster builds, lower compression defineAlgorithm('gzip', { level: 6 }), // Default level // Production: slower builds, better compression defineAlgorithm('gzip', { level: 9 }), // Maximum compression // Brotli: quality 10-11 recommended for static assets defineAlgorithm('brotliCompress', { params: { [require('zlib').constants.BROTLI_PARAM_QUALITY]: 11 } }) ] }) ``` -------------------------------- ### Enable both gzip and brotli compression Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Configure the plugin to use both gzip and brotli compression by including them in the `algorithms` array. This provides optimal compression for modern browsers while maintaining compatibility with older ones. ```javascript compression({ algorithms: ['gzip', 'brotliCompress'] }) ``` -------------------------------- ### Nginx Configuration for Compressed Files Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt Configure Nginx to automatically serve pre-compressed .gz and .br files. Enables dynamic compression as a fallback. ```nginx # nginx — serve pre-compressed .gz and .br files automatically http { gzip_static on; # serve .gz (built-in module) brotli_static on; # serve .br (requires ngx_brotli) gzip on; # dynamic fallback for clients without pre-compressed file gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript; server { listen 80; root /var/www/html; location / { try_files $uri $uri/ /index.html; } location ~* \.(js|css|html)$ { expires 1y; add_header Cache-Control "public, immutable"; add_header Vary "Accept-Encoding"; } } } ``` -------------------------------- ### defineAlgorithm(algorithm, options?) Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt Creates a typed algorithm tuple for use with the compression plugin. It merges supplied options over the algorithm's built-in defaults and accepts a named algorithm string or a custom async function. ```APIDOC ## defineAlgorithm(algorithm, options?) ### Description Creates a typed `[algorithm, options]` tuple consumed by the `algorithms` array. Merges supplied options over the algorithm's built-in defaults. Accepts a named algorithm string or a fully custom async function. ### Parameters * `algorithm` (string | Function): The name of the algorithm (e.g., 'gzip', 'brotliCompress') or a custom async compression function. * `options` (object, optional): Configuration options for the algorithm. ### Examples 1. **Named algorithm with defaults** ```ts import { defineAlgorithm } from 'vite-plugin-compression2' defineAlgorithm('gzip') // → ['gzip', { level: zlib.constants.Z_BEST_COMPRESSION }] ``` 2. **Named algorithm with partial override** ```ts import { defineAlgorithm } from 'vite-plugin-compression2' defineAlgorithm('gzip', { level: 6 }) // → ['gzip', { level: 6 }] ``` 3. **Brotli with explicit quality** ```ts import { defineAlgorithm } from 'vite-plugin-compression2' import zlib from 'zlib' defineAlgorithm('brotliCompress', { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11, [zlib.constants.BROTLI_PARAM_LGWIN]: 24 } }) ``` 4. **Zstandard** ```ts import { defineAlgorithm } from 'vite-plugin-compression2' defineAlgorithm('zstandard', { params: { [zlib.constants.ZSTD_c_compressionLevel]: 19 } }) ``` 5. **Algorithm aliases** ```ts defineAlgorithm('gz') // → 'gzip' defineAlgorithm('br') // → 'brotliCompress' defineAlgorithm('brotli') // → 'brotliCompress' defineAlgorithm('zstd') // → 'zstandard' ``` 6. **Fully custom async compression function** ```ts import { defineAlgorithm } from 'vite-plugin-compression2' import zlib from 'zlib' import util from 'util' const lz4Like = defineAlgorithm( async (buf: Buffer, options: { quality: number }): Promise => { return util.promisify(zlib.gzip)(buf, { level: options.quality }) }, { quality: 9 } ) ``` ``` -------------------------------- ### Multiple Algorithms with Custom Options Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Configures multiple compression algorithms, including custom options for Brotli quality. ```javascript compression({ algorithms: [ defineAlgorithm('gzip', { level: 9 }), defineAlgorithm('brotliCompress', { params: { [require('zlib').constants.BROTLI_PARAM_QUALITY]: 11 } }) ] }) ``` -------------------------------- ### Basic Algorithm Configuration Migration Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Migrate basic algorithm configuration from v1.x's `algorithm` option to v2.x's `algorithms` array with `defineAlgorithm`. ```javascript // Old compression({ algorithm: 'gzip', compressionOptions: { level: 9 } }) // New compression({ algorithms: [defineAlgorithm('gzip', { level: 9 })] }) ``` -------------------------------- ### Default Gzip Migration Pattern Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Shows the migration pattern for default gzip compression from v1.x to v2.x, noting that the default behavior remains the same. ```javascript // v1.x compression() // v2.x compression() // Still works! Defaults to ['gzip', 'brotliCompress'] ``` -------------------------------- ### Define Built-in Compression Algorithm Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Use defineAlgorithm to specify a built-in compression algorithm with its default options. ```javascript defineAlgorithm('gzip') ``` -------------------------------- ### Nginx Configuration for Static Compression Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Nginx configuration to serve pre-compressed .gz and .br files using gzip_static and brotli_static modules. ```nginx http { # Enable gzip_static module to serve pre-compressed .gz files gzip_static on; # Enable brotli_static to serve pre-compressed .br files # Requires ngx_brotli module: https://github.com/google/ngx_brotli brotli_static on; # Fallback to dynamic compression if static file not found gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; server { listen 80; server_name example.com; root /var/www/html; location / { try_files $uri $uri/ /index.html; } } } ``` -------------------------------- ### Apply Custom Compression Options with defineAlgorithm Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md When using custom compression options, ensure `defineAlgorithm` is used correctly. The incorrect approach directly assigns an array, while the correct approach wraps the algorithm and its options within `defineAlgorithm`. ```javascript // Wrong algorithms: ;['gzip'] ``` ```javascript // Correct with options algorithms: ;[defineAlgorithm('gzip', { level: 9 })] ``` -------------------------------- ### Custom Algorithm Implementation Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Define and use a custom compression algorithm function with `defineAlgorithm` in v2.x, specifying the buffer, options, and custom configuration. ```javascript const customAlgorithm = defineAlgorithm( async (buffer: Buffer, options: { quality: number }) => { // Custom compression implementation return compressedBuffer; }, { quality: 8 } ); ``` -------------------------------- ### Nginx Configuration for Pre-compressed Files Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Configure Nginx to serve pre-compressed gzip and brotli files. Ensure 'gzip_static' and 'brotli_static' are enabled. ```nginx events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; # Enable pre-compressed file serving gzip_static on; brotli_static on; # Fallback dynamic compression gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; server { listen 80; server_name localhost; root /usr/share/nginx/html; index index.html; location / { try_files $uri $uri/ /index.html; } } } ``` -------------------------------- ### Mixed Algorithm Types with Custom Functions Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Configure a mix of built-in and custom compression algorithms using `defineAlgorithm` in v2.x. ```javascript import { compression, defineAlgorithm } from 'vite-plugin-compression2' compression({ algorithms: [ // Built-in algorithm 'gzip', // Built-in algorithm with options defineAlgorithm('brotliCompress', { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 8 } }), // Custom algorithm function defineAlgorithm( async (buffer, options) => { // Your custom compression logic return compressedBuffer }, { customOption: true } ) ] }) ``` -------------------------------- ### compression() plugin configuration Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt Configures the compression plugin, allowing specification of algorithms, deletion of original assets, and more. ```APIDOC ## compression(options) ### Description Applies compression to Vite output assets. The `algorithms` option accepts string shorthands, `defineAlgorithm()` tuples, and raw alias tuples interchangeably. ### Parameters * `options` (object): Configuration options for the compression plugin. * `algorithms` (Array): An array specifying the compression algorithms to use. Can include string shorthands (e.g., 'gzip'), `defineAlgorithm()` tuples, or raw alias tuples. * `deleteOriginalAssets` (boolean, optional): Whether to delete original assets after compression. Defaults to `true`. * `skipIfLargerOrEqual` (boolean, optional): Whether to emit compressed files even if they are not smaller than the original. Defaults to `true`. ### Examples **Configuring multiple algorithms** ```ts import { compression, defineAlgorithm } from 'vite-plugin-compression2' import zlib from 'zlib' compression({ algorithms: [ 'gzip', 'brotliCompress', defineAlgorithm('deflate', { level: 9 }), defineAlgorithm('deflateRaw', { level: 9 }), defineAlgorithm('zstandard', { params: { [zlib.constants.ZSTD_c_compressionLevel]: 19 } }), ['br', {}] as const // alias for brotliCompress ], skipIfLargerOrEqual: false }) ``` ``` -------------------------------- ### Implement Multi-Algorithm Compression Strategy Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Utilize both gzip and brotli compression to maximize compatibility with older browsers (gzip) and achieve better compression ratios with modern browsers (brotli). The server automatically serves the best format based on the `Accept-Encoding` header. ```javascript compression({ algorithms: [ defineAlgorithm('gzip', { level: 9 }), // Wide browser support (all browsers) defineAlgorithm('brotliCompress', { // Better compression (modern browsers) params: { [require('zlib').constants.BROTLI_PARAM_QUALITY]: 11 } }) ] }) ``` -------------------------------- ### Define Custom Compression Algorithm Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Use `defineAlgorithm` to create custom compression logic or configure built-in algorithms with specific options. This allows for fine-grained control over the compression process. ```typescript import { defineAlgorithm } from 'vite-plugin-compression2' // Built-in algorithm with custom options const gzipAlgorithm = defineAlgorithm('gzip', { level: 9 }) // Custom algorithm function const customAlgorithm = defineAlgorithm( async (buffer, options) => { // Your custom compression logic return compressedBuffer }, { customLevel: 5 } ) ``` -------------------------------- ### Define Built-in Compression Algorithm with Custom Options Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Configure a built-in compression algorithm by providing custom options, such as compression level. ```javascript defineAlgorithm('gzip', { level: 9 }) ``` -------------------------------- ### Multiple Algorithms Configuration Migration Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Update configurations that previously required multiple plugin instances for different algorithms to a single instance using the `algorithms` array in v2.x. ```javascript // Old - Multiple plugin instances compression({ algorithm: 'gzip' }), compression({ algorithm: 'brotliCompress' }) // New compression({ algorithms: [ defineAlgorithm('gzip', { level: 9 }), defineAlgorithm('brotliCompress', { params: { [require('zlib').constants.BROTLI_PARAM_QUALITY]: 11 } }) ] }) ``` -------------------------------- ### Optimize Compression Settings Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Optimize compression settings by skipping small files, excluding unnecessary file types like source maps and text files, and using only gzip for faster builds in CI environments. ```javascript compression({ threshold: 1024, exclude: [/\.map$/, /\.txt$/], algorithms: ['gzip'], }) ``` -------------------------------- ### Apache Configuration for Static Compression Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Apache configuration using mod_rewrite to serve pre-compressed .br and .gz files based on client Accept-Encoding headers. ```apache # Enable mod_deflate for fallback dynamic compression AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json # Serve pre-compressed files RewriteEngine On # Serve .br file if it exists and client supports brotli RewriteCond %{HTTP:Accept-Encoding} br RewriteCond %{REQUEST_FILENAME}.br -f RewriteRule ^(.*)$ $1.br [L] # Serve .gz file if it exists and client supports gzip RewriteCond %{HTTP:Accept-Encoding} gzip RewriteCond %{REQUEST_FILENAME}.gz -f RewriteRule ^(.*)$ $1.gz [L] # Set correct content-type and encoding headers Header set Content-Type "application/javascript" Header set Content-Encoding "gzip" Header set Content-Type "text/css" Header set Content-Encoding "gzip" Header set Content-Type "application/javascript" Header set Content-Encoding "br" Header set Content-Type "text/css" Header set Content-Encoding "br" ``` -------------------------------- ### Verify Compressed Files Exist Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt Check the output directory (e.g., 'dist/assets/') to confirm that the compressed sidecar files (.gz and .br) have been generated. ```bash # Check that compressed sidecar files exist in dist/ ls dist/assets/*.gz dist/assets/*.br ``` -------------------------------- ### Nginx Configuration for Compressed Files Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Configure Nginx to serve pre-compressed files by enabling the `gzip_static` module. This allows Nginx to serve `.gz` or `.br` files directly when available. ```nginx # Enable gzip_static module gzip_static on; ``` -------------------------------- ### Update Multiple Instances to Single Instance Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Consolidate multiple plugin instances for different compression algorithms into a single instance with the `algorithms` array in v2.x. ```javascript // Old - Multiple plugin instances export default defineConfig({ plugins: [ compression({ algorithm: 'gzip' }), compression({ algorithm: 'brotliCompress' }) ] }) // New - Single plugin instance export default defineConfig({ plugins: [ compression({ algorithms: ['gzip', 'brotliCompress'] }) ] }) ``` -------------------------------- ### Configure Compressed Filename with Templates Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt Use template tokens like [path] and [base] or a function to define the output path and name for compressed files. The default is '[path][base].gz'. ```typescript import { compression, defineAlgorithm } from 'vite-plugin-compression2' // Template tokens: // [path] → directory portion of the asset path, with trailing slash (e.g. "assets/") // [base] → full filename including extension (e.g. "main.abc123.js") compression({ algorithms: ['gzip'], filename: '[path][base].gz' // default — assets/main.abc123.js.gz }) compression({ algorithms: ['gzip'], filename: 'fake/[base].gz' // all compressed files go under dist/fake/ }) // Amazon S3 / CDN pattern: replace file in place (no extra extension) compression({ algorithms: ['gzip'], filename: '[path][base]', // overwrites original path with compressed content deleteOriginalAssets: true // remove the uncompressed original }) // Function form: per-algorithm file naming compression({ algorithms: [defineAlgorithm('gzip'), defineAlgorithm('brotliCompress')], filename: (id, { algorithm }) => { return algorithm === 'brotliCompress' ? `${id}.br` : `${id}.gz` } }) ``` -------------------------------- ### Consolidate Multiple Plugin Instances Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Avoid using multiple instances of the compression plugin. Instead, combine algorithms into a single instance by passing an array of algorithms to the `algorithms` option. ```javascript // Old approach compression({ algorithm: 'gzip' }), compression({ algorithm: 'brotliCompress' }) ``` ```javascript // New approach compression({ algorithms: ['gzip', 'brotliCompress'] }) ``` -------------------------------- ### Define Compression Algorithm with Options Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt Use `defineAlgorithm` to create typed tuples for compression algorithms. This function merges supplied options over the algorithm's defaults and accepts named algorithms or custom async functions. It's useful for configuring specific compression levels or parameters. ```typescript import { defineAlgorithm } from 'vite-plugin-compression2' import zlib from 'zlib' import util from 'util' // 1. Named algorithm with defaults const gz = defineAlgorithm('gzip') // → ['gzip', { level: zlib.constants.Z_BEST_COMPRESSION }] // 2. Named algorithm with partial override (merged over defaults) const fastGzip = defineAlgorithm('gzip', { level: 6 }) // → ['gzip', { level: 6 }] // 3. Brotli with explicit quality const brotli = defineAlgorithm('brotliCompress', { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11, // 0–11; 11 = maximum [zlib.constants.BROTLI_PARAM_LGWIN]: 24 } }) // 4. Zstandard (requires Node.js >= 22.15.0 or >= 23.8.0) const zstd = defineAlgorithm('zstandard', { params: { [zlib.constants.ZSTD_c_compressionLevel]: 19 } }) // 5. Algorithm aliases — resolved automatically defineAlgorithm('gz') // → 'gzip' defineAlgorithm('br') // → 'brotliCompress' defineAlgorithm('brotli') // → 'brotliCompress' defineAlgorithm('zstd') // → 'zstandard' // 6. Fully custom async compression function const lz4Like = defineAlgorithm( async (buf: Buffer, options: { quality: number }): Promise => { // buf is the raw asset bytes; return the compressed Buffer return util.promisify(zlib.gzip)(buf, { level: options.quality }) }, { quality: 9 } ) // Use in plugin: // compression({ algorithms: [gz, fastGzip, brotli, lz4Like] }) ``` -------------------------------- ### tarball(options?) Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt Packs all Vite output files into a ustar `.tar` archive. This plugin should be used after the `compression` plugin to include compressed files in the archive. ```APIDOC ## tarball(options?) ### Description Packs all Vite output files (including any compressed files produced by `compression`) into a ustar `.tar` archive. Compatible with gnutar, bsdtar, and other popular tar distributions. Use it **after** `compression` in the plugins array so compressed files are included in the archive. ### Parameters * `options` (object, optional): Configuration options for the tarball plugin. * `dest` (string, optional): The destination path for the `.tar` archive. Defaults to the build output directory. ### Examples **Using tarball with compression** ```ts import { defineConfig } from 'vite' import { compression, tarball } from 'vite-plugin-compression2' export default defineConfig({ plugins: [ compression({ algorithms: ['gzip', 'brotliCompress'], deleteOriginalAssets: false }), tarball({ dest: './dist/archive' }) ] }) // Output: dist/archive.tar ``` **Using tarball standalone** ```ts import { defineConfig } from 'vite' import { tarball } from 'vite-plugin-compression2' export default defineConfig({ plugins: [ tarball({ dest: './release' }) ] }) // Output: release.tar ``` ``` -------------------------------- ### Node.js Script for Post-Build Compression Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md A Node.js script that utilizes vite-plugin-compression to compress files in an existing 'dist' folder after the initial build. Ensure 'emptyOutDir' is set to false to preserve existing build artifacts. ```javascript import { compression } from 'vite-plugin-compression2' import { build } from 'vite' // Run compression on existing dist folder await build({ build: { emptyOutDir: false }, plugins: [ compression({ algorithms: ['gzip', 'brotliCompress'] }) ] }) ``` -------------------------------- ### Verify compression with curl Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Use `curl` with the `Accept-Encoding` header to check if the server is correctly serving compressed files. This helps verify that gzip or brotli compression is working as expected. ```bash curl -I -H "Accept-Encoding: gzip" https://your-site.com/main.js # Should see: Content-Encoding: gzip ``` ```bash curl -I -H "Accept-Encoding: br" https://your-site.com/main.js # Should see: Content-Encoding: br ``` -------------------------------- ### Vite Plugin Compression with Multiple Algorithms Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Configure the plugin to use multiple compression algorithms, including custom deflate levels. ```javascript import { compression, defineAlgorithm } from 'vite-plugin-compression2' export default defineConfig({ plugins: [ compression({ algorithms: [ 'gzip', 'brotliCompress', defineAlgorithm('deflate', { level: 9 }) ] }) ] }) ``` -------------------------------- ### Configure Compression Algorithms with Mixed Types Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt The `algorithms` option in `compression` accepts a flexible array containing string shorthands, `defineAlgorithm()` tuples, and raw alias tuples. This allows for a mix of default, custom, and aliased compression methods in a single configuration. ```typescript import { compression, defineAlgorithm } from 'vite-plugin-compression2' import zlib from 'zlib' compression({ algorithms: [ // String shorthand — uses built-in defaults 'gzip', 'brotliCompress', // defineAlgorithm tuple — custom options defineAlgorithm('deflate', { level: 9 }), defineAlgorithm('deflateRaw', { level: 9 }), defineAlgorithm('zstandard', { params: { [zlib.constants.ZSTD_c_compressionLevel]: 19 } }), // Raw alias tuple (low-level) ['br', {}] as const, ], skipIfLargerOrEqual: false // emit compressed file even if no savings }) ``` -------------------------------- ### compression(options?) Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt The main Vite plugin that registers the compression functionality. It hooks into Vite's build process to compress bundled assets. All options are optional, with sensible defaults provided. ```APIDOC ## compression(options?) ### Description Registers the compression plugin in the Vite plugin pipeline. Applies only during `build` mode (`apply: 'build'`, `enforce: 'post'`). All options are optional; defaults produce gzip + brotli output for common text-based file types. ### Parameters #### Options Object - **include** (RegExp | string | string[]) - Optional - File-matching pattern (rollup filterPattern) for assets to compress. Defaults to common text-based file types. - **exclude** (RegExp | string | string[]) - Optional - Pattern for assets to exclude from compression. Defaults to skipping source maps and `.txt` files. - **threshold** (number) - Optional - Minimum file size in bytes to be compressed. Defaults to 0 (compress all files). - **algorithms** (Array) - Optional - An array of compression algorithms to use. Can be string shorthands (e.g., 'gzip') or `defineAlgorithm()` tuples with custom options. Defaults to gzip and brotliCompress. - **filename** (string | function) - Optional - Output filename template. Can use tokens like `[path]` and `[base]`, or a function for dynamic naming. Defaults to `[path][base].gz` or `[path][base].br`. - **deleteOriginalAssets** (boolean) - Optional - If true, removes original assets after successful compression. Defaults to `false`. - **skipIfLargerOrEqual** (boolean) - Optional - If true, discards compressed files if they are larger than or equal to the original file size. Defaults to `true`. - **logLevel** ('info' | 'silent') - Optional - Controls the verbosity of plugin logs. Defaults to 'info'. - **artifacts** (function) - Optional - A function that returns an array of files to be copied into the output directory before compression. Each artifact can have `src` and `replace` properties. - **scheduler** (SchedulerOptions) - Optional - Configuration for limiting concurrency of high-memory compression tasks. Includes `limit` (max simultaneous tasks) and `isHighMemory` (function to identify high-memory algorithms). ### Example Usage ```ts // vite.config.ts import { defineConfig } from 'vite' import { compression, defineAlgorithm } from 'vite-plugin-compression2' import zlib from 'zlib' export default defineConfig({ plugins: [ compression({ include: /\.(html|xml|css|json|js|mjs|svg|yaml|yml|toml)$/, exclude: [\.map$/, \.txt$/], threshold: 1024, algorithms: [ 'gzip', defineAlgorithm('brotliCompress', { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11 } }), defineAlgorithm('deflate', { level: 9 }) ], filename: '[path][base].gz', deleteOriginalAssets: false, skipIfLargerOrEqual: true, logLevel: 'info', artifacts: () => [ { src: 'node_modules/some-lib/runtime.js' }, { src: 'node_modules/some-lib/worker.js', replace: (dest, filename) => path.join(dest, 'workers', filename) } ], scheduler: { limit: 1, isHighMemory: (alg, opts) => alg === 'brotliCompress' } }) ] }) ``` ``` -------------------------------- ### Generate Multiple Compressed Assets Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Configure the plugin to generate multiple compressed assets using different algorithms simultaneously. This is useful for supporting various compression methods on the client side. ```typescript import { defineConfig } from 'vite' import { compression, defineAlgorithm } from 'vite-plugin-compression2' export default defineConfig({ plugins: [ compression({ algorithms: [ 'gzip', 'brotliCompress', defineAlgorithm('deflate', { level: 9 }) ] }) ] }) ``` -------------------------------- ### Define Compression Algorithms Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Configure the compression algorithms to be used. Accepts an array of algorithm names or custom defined algorithms with options. ```typescript type Algorithms = | Algorithm[] // ['gzip', 'brotliCompress'] | DefineAlgorithmResult[] // [defineAlgorithm('gzip'), ...] | (Algorithm | DefineAlgorithmResult)[] // Mixed array ``` -------------------------------- ### defineAlgorithm Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Defines a compression algorithm with optional configurations. This function allows users to specify built-in algorithms with custom options or provide their own custom compression logic. ```APIDOC ## defineAlgorithm(algorithm, options?) ### Description Define a compression algorithm with options. ### Parameters - **algorithm**: Algorithm name (`'gzip' | 'brotliCompress' | 'deflate' | 'deflateRaw' | 'zstandard' | 'gz' | 'br' | 'brotli' | 'zstd'`) or custom function - **options**: Compression options for the algorithm ### Returns `[algorithm, options]` tuple ### Examples ```js // Built-in algorithm with default options defineAlgorithm('gzip') // Built-in algorithm with custom options defineAlgorithm('gzip', { level: 9 }) // Brotli with custom quality defineAlgorithm('brotliCompress', { params: { [require('zlib').constants.BROTLI_PARAM_QUALITY]: 11 } }) // Custom algorithm function defineAlgorithm( async (buffer, options) => { // Your compression implementation return compressedBuffer }, { customOption: 'value' } ) ``` ``` -------------------------------- ### Vite Plugin Compression with Custom Algorithm Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Implement and use a custom compression logic within the plugin configuration. ```javascript import { compression, defineAlgorithm } from 'vite-plugin-compression2' export default defineConfig({ plugins: [ compression({ algorithms: [ defineAlgorithm( async (buffer, options) => { // Your custom compression logic return compressedBuffer }, { customOption: true } ) ] }) ] }) ``` -------------------------------- ### Configure vite-plugin-compression2 Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt Use the compression plugin in vite.config.ts to customize asset compression. Configure file matching, size thresholds, compression algorithms, output filenames, and more. Ensure necessary imports from 'vite' and 'vite-plugin-compression2'. ```typescript import { defineConfig } from 'vite' import { compression, defineAlgorithm } from 'vite-plugin-compression2' import zlib from 'zlib' export default defineConfig({ plugins: [ compression({ // File-matching (rollup filterPattern) include: /\.(html|xml|css|json|js|mjs|svg|yaml|yml|toml)$/, // default exclude: [/\.map$/, /\.txt$/], // skip source maps // Size gate threshold: 1024, // skip files smaller than 1 KB (bytes); default 0 // Algorithms — string shorthand OR defineAlgorithm() tuples, mixed freely algorithms: [ 'gzip', // shorthand, uses default options defineAlgorithm('brotliCompress', { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 11 } }), defineAlgorithm('deflate', { level: 9 }), ], // Output filename template; tokens: [path], [base] // Default: '[path][base].gz' / '[path][base].br' / '[path][base].zst' filename: '[path][base].gz', // OR a function for dynamic names: // filename: (id, { algorithm, options }) => `${id}.${algorithm === 'brotliCompress' ? 'br' : 'gz'}`, deleteOriginalAssets: false, // remove originals after compression skipIfLargerOrEqual: true, // discard compressed file if it's >= original size logLevel: 'info', // 'info' | 'silent' // Copy extra files into the output directory before compression artifacts: () => [ { src: 'node_modules/some-lib/runtime.js' }, { src: 'node_modules/some-lib/worker.js', replace: (dest, filename) => path.join(dest, 'workers', filename) } ], // Concurrency limiter for high-memory algorithms (see SchedulerOptions) scheduler: { limit: 1, // max simultaneous high-memory tasks; default 1 isHighMemory: (alg, opts) => alg === 'brotliCompress' } }) ] }) ``` -------------------------------- ### Basic Gzip Compression Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Enables only gzip compression for assets. ```javascript compression({ algorithms: ['gzip'] }) ``` -------------------------------- ### Define Custom Compression Algorithm Function Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Implement and register a custom compression algorithm using an asynchronous function. Ensure your function handles buffer compression and returns the compressed buffer. ```javascript defineAlgorithm( async (buffer, options) => { // Your compression implementation return compressedBuffer }, { customOption: 'value' } ) ``` -------------------------------- ### Vite Plugin Compression with Tarball Creation Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Combine the compression plugin with the tarball plugin to create archive files of compressed assets. ```javascript import { compression, tarball } from 'vite-plugin-compression2' export default defineConfig({ plugins: [ compression(), // If you want to create a tarball archive, use tarball plugin after compression tarball({ dest: './dist/archive' }) ] }) ``` -------------------------------- ### Size Threshold for Compression Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Sets a minimum file size threshold (in bytes) for assets to be considered for compression. ```javascript compression({ algorithms: ['gzip'], threshold: 1000 // Only compress files larger than 1KB }) ``` -------------------------------- ### Define Brotli Compression with Custom Quality Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Customize the Brotli compression algorithm by setting specific parameters, like the quality level. ```javascript defineAlgorithm('brotliCompress', { params: { [require('zlib').constants.BROTLI_PARAM_QUALITY]: 11 } }) ``` -------------------------------- ### Create Tarball Archive with Vite Plugin Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt The `tarball` plugin packs all Vite output files into a ustar `.tar` archive. It should be used after the `compression` plugin to include compressed files. The `dest` option specifies the output path for the archive. ```typescript import { defineConfig } from 'vite' import { compression, tarball } from 'vite-plugin-compression2' export default defineConfig({ plugins: [ compression({ algorithms: ['gzip', 'brotliCompress'], deleteOriginalAssets: false }), // tarball runs after compression; the .tar will contain both originals and .gz/.br files tarball({ dest: './dist/archive' // writes dist/archive.tar; directory is created if absent // dest defaults to the build output directory when omitted }) ] }) // Output: dist/archive.tar (ustar format, all bundle + public assets inside) // tarball can also be used standalone without compression: // plugins: [ tarball({ dest: './release' }) ] ``` -------------------------------- ### Set File Size Threshold for Compression Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Only compress files that exceed a specified size threshold to avoid unnecessary processing of small files. A 1KB threshold is recommended to ensure compression benefits outweigh overhead. ```javascript compression({ threshold: 1024, // 1KB minimum - recommended algorithms: ['gzip', 'brotliCompress'] }) ``` -------------------------------- ### Simplified Array Syntax for Algorithms Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Use the simplified array syntax in v2.x for specifying algorithms, which automatically applies default options. ```javascript compression({ algorithms: ['gzip', 'brotliCompress'] // Auto-uses default options }) ``` -------------------------------- ### Include Extra Files with Artifacts Source: https://context7.com/nonzzz/vite-plugin-compression/llms.txt Use the artifacts option to copy additional files into the output directory before compression. You can specify a custom destination path using a replace function. ```typescript import path from 'path' import { compression } from 'vite-plugin-compression2' compression({ algorithms: ['gzip', 'brotliCompress'], artifacts: () => [ // Copy file at its original basename into the output root { src: 'node_modules/some-lib/dist/runtime.js' }, // Copy with a custom destination path { src: 'node_modules/some-lib/dist/worker.js', replace: (dest, filename) => path.join(dest, 'workers', filename) // dest = resolved vite outDir (e.g. /project/dist) // filename = basename of src (e.g. worker.js) // return value = full absolute destination path } ] }) ``` -------------------------------- ### Update Import Statement Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Adjust the import statement to include `defineAlgorithm` when migrating from v1.x to v2.x. ```javascript // Old import { compression } from 'vite-plugin-compression2' // New import { compression, defineAlgorithm } from 'vite-plugin-compression2' ``` -------------------------------- ### TypeScript Errors Solution Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/MIGRATION-GUIDE.md Provides a solution for TypeScript errors encountered during migration by ensuring `defineAlgorithm` is imported. ```javascript import { compression, defineAlgorithm } from 'vite-plugin-compression2' ``` -------------------------------- ### Custom Filename Pattern Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Specifies a custom filename pattern for compressed assets, including path, base name, hash, and extension. ```javascript compression({ algorithms: ['gzip'], filename: '[path][base].[hash].gz' }) ``` -------------------------------- ### Conditionally Compress Source Maps Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md An alternative configuration for compressing source maps only if they exceed a certain size threshold. This uses only gzip for faster builds. ```javascript compression({ include: [/\.(js|css|html|json|svg|map)$/], threshold: 10240, algorithms: ['gzip'] }) ``` -------------------------------- ### Configure Selective File Compression Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/README.md Compress only specific file types that benefit from compression, such as text-based files, and exclude already compressed formats like images and fonts. This optimizes build times and storage. ```javascript compression({ include: [/\.(js|mjs|json|css|html|svg)$/], // Text-based files exclude: [/\.(png|jpg|jpeg|gif|webp|woff|woff2)$/], // Already compressed formats threshold: 1024 }) ``` -------------------------------- ### Customize filename patterns for compressed assets Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Use the `filename` option to specify custom naming patterns for compressed files. This can be a string pattern or a function for dynamic naming based on the asset and algorithm. ```typescript compression({ algorithms: ['gzip'], filename: '[path][base].[hash].gz' // Custom pattern }) ``` ```typescript compression({ algorithms: [defineAlgorithm('gzip')], filename: (id, { algorithm }) => { return algorithm === 'gzip' ? `${id}.gz` : `${id}.br` } }) ``` -------------------------------- ### Use Tarball Plugin Independently Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md The `tarball` plugin can be used independently for creating archives without compression. Specify the destination directory for the archive. ```typescript import { tarball } from 'vite-plugin-compression2' export default defineConfig({ plugins: [ tarball({ dest: './dist/archive' }) ] }) ``` -------------------------------- ### Nginx Cache Control for Compressed Assets Source: https://github.com/nonzzz/vite-plugin-compression/blob/master/Q&A.md Set cache control headers for compressed JavaScript, CSS, and HTML files to ensure proper CDN caching. This configuration sets an expiration of 1 year and includes the Vary header for Accept-Encoding. ```nginx location ~* \.(js|css|html)$ { expires 1y; add_header Cache-Control "public, immutable"; add_header Vary "Accept-Encoding"; } ```