vite-plugin-compression2

repository·master·Indexed 43 days ago

https://github.com/nonzzz/vite-plugin-compression

A fast Vite plugin that generates compressed versions of assets (such as gzip, brotli, or zstandard) during the build process to reduce CPU usage and improve load times. Version 2.5.3 supports multiple compression algorithms via a single plugin instance, custom algorithm implementation through defineAlgorithm, and the creation of tarball archives.

Tokens
10.6K
Snippets
37
Records
44
Agent score
55%

What's inside vite-plugin-compression2

  1. Implement a multi-algorithm strategy (gzip and brotli)

    master

    For maximum compatibility and performance, provide both gzip and brotliCompress.

    • Brotli provides 15-20% better compression than gzip and is ideal for modern browsers.
    • Gzip serves as a fallback for older browsers.

    When both are provided, the server can automatically serve the best format based on the client's Accept-Encoding header.

    compression({
      algorithms: [
        defineAlgorithm('gzip', { level: 9 }), // Wide browser support
        defineAlgorithm('brotliCompress', { // Better compression
          params: {
            [require('zlib').constants.BROTLI_PARAM_QUALITY]: 11
          }
        })
      ]
    })
  2. Selectively compress specific file types

    master

    Optimize your build by using include and exclude regex patterns to target only text-based files that compress well, while skipping already-compressed formats like images and fonts.

    Recommended targets:

    • JavaScript/TypeScript (.js, .mjs, .ts)
    • CSS (.css)
    • HTML (.html)
    • JSON (.json)
    • SVG (.svg)
    • XML (.xml)

    Recommended exclusions:

    • Images (.png, .jpg, .webp, etc.)
    • Fonts (.woff, .woff2)
    • Videos (.mp4, .webm)
    compression({
      include: [/\.(js|mjs|json|css|html|svg)$/], // Text-based files
      exclude: [/\.(png|jpg|jpeg|gif|webp|woff|woff2)$/], // Already compressed formats
      threshold: 1024
    })
  3. Run the vite-plugin-compression2-starter example

    master

    To explore the plugin in a working environment, you can use the provided starter example. Follow these steps to install dependencies, build the project, and preview the compressed assets locally:

    $ yarn // install dependices
    
    $ yarn build // packing static resources
    
    $ yarn preview // start a local server to preivew the result.
  4. Run compression as a separate build step

    master

    If you prefer not to run compression during the main Vite build, you can trigger it manually using a script that calls build from vite with the compression plugin applied to an existing directory.

    // compress.js
    import { compression } from 'vite-plugin-compression2'
    import { build } from 'vite'
    
    // Run compression on existing dist folder
    await build({
      build: {
        emptyOutDir: false // Don't delete existing files
      },
      plugins: [
        compression({
          algorithms: ['gzip', 'brotliCompress']
        })
      ]
    })
  5. Use a file size threshold to skip small files

    master

    To avoid wasting build time and disk space on files that don't benefit from compression, use the threshold option. It is recommended to set a minimum threshold (e.g., 1024 bytes) because files smaller than 1KB may actually increase in size due to HTTP overhead or provide negligible benefits.

    compression({
      threshold: 1024, // 1KB minimum - recommended
      algorithms: ['gzip', 'brotliCompress']
    })
  6. Configure Nginx to serve pre-compressed assets

    master

    To serve .gz and .br files generated by the plugin, enable the gzip_static and brotli_static modules in your Nginx configuration. This allows Nginx to serve the pre-compressed files directly instead of compressing them on the fly.

    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;
            }
        }
    }
  7. Verify compression is working

    master

    To ensure your assets are being served correctly with compression, follow these steps:

    1. Check build output: Verify that .gz or .br files exist in your dist folder.
    2. Check response headers: Use curl to inspect the Content-Encoding header. The client must send an Accept-Encoding header.
    3. Compare file sizes: In browser DevTools (Network tab), compare the Size (actual file size) against the Transferred (compressed size sent over network).

    Example curl command:

    curl -I -H "Accept-Encoding: gzip" https://your-site.com/main.js
    # Should see: Content-Encoding: gzip
  8. How to use compressed assets with NGINX

    master
    The starter example demonstrates a simple usage pattern. If you intend to serve the compressed assets using a production web server like NGINX, you must configure your server to handle the compressed files (e.g., via the ngx_http_gzip_module). Refer to the official NGINX documentation for specific configuration details.
  9. Configure Apache to serve pre-compressed assets

    master

    To serve pre-compressed files on Apache, use mod_rewrite to check for the existence of .br or .gz versions of a file and serve them if the client's Accept-Encoding header supports them. You must also set the correct Content-Encoding headers.

    # Enable mod_deflate for fallback dynamic compression
    <IfModule mod_deflate.c>
        AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
    </IfModule>
    
    # Serve pre-compressed files
    <IfModule mod_rewrite.c>
        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]
    </IfModule>
    
    # Set correct content-type and encoding headers
    <FilesMatch "\.js\.gz$">
        Header set Content-Type "application/javascript"
        Header set Content-Encoding "gzip"
    </FilesMatch>
    
    <FilesMatch "\.css\.gz$">
        Header set Content-Type "text/css"
        Header set Content-Encoding "gzip"
    </FilesMatch>
    
    <FilesMatch "\.js\.br$">
        Header set Content-Type "application/javascript"
        Header set Content-Encoding "br"
    </FilesMatch>
    
    <FilesMatch "\.css\.br$">
        Header set Content-Type "text/css"
        Header set Content-Encoding "br"
    </FilesMatch>
  10. Migrate from v1.x to v2.x

    master

    When upgrading from vite-plugin-compression2 v1.x to v2.x, you must address several breaking changes regarding how algorithms are configured.

    Key Breaking Changes

    1. algorithm → algorithms: The single algorithm string option is replaced by an algorithms array.
    2. Removal of compressionOptions: You can no longer pass a separate compressionOptions object. Instead, use the defineAlgorithm() helper function to associate options directly with an algorithm.
    3. Plugin Consolidation: Instead of creating multiple plugin instances for different algorithms, you should now use a single plugin instance with multiple entries in the algorithms array.

    Step-by-Step Migration

    1. Update Package:

      npm install vite-plugin-compression2@latest -D
    2. Update Imports: Ensure you import defineAlgorithm alongside compression:

      import { compression, defineAlgorithm } from 'vite-plugin-compression2'
    3. Update Configuration:

      • Simple case: Change algorithm: 'gzip' to algorithms: ['gzip'].
      • With options: Use defineAlgorithm('gzip', { level: 6 }) inside the algorithms array.
      • Multiple algorithms: Combine multiple instances into one:
        // v1.x
        plugins: [compression({ algorithm: 'gzip' }), compression({ algorithm: 'brotliCompress' })]
        
        // v2.x
        plugins: [compression({ algorithms: ['gzip', 'brotliCompress'] })]
    npm install vite-plugin-compression2@latest -D
  11. Optimize compression levels for different environments

    master

    You can tune the compression intensity by using defineAlgorithm to set specific levels. This allows you to balance build speed against file size depending on your deployment stage.

    • Development/CI: Use lower levels (e.g., gzip level 6 or brotli quality 4-6) for faster builds.
    • Production: Use maximum levels (e.g., gzip level 9 or brotli quality 10-11) for the best compression ratio.
    • Balance: Use mid-range levels (e.g., gzip level 7-8 or brotli quality 8-9).
    compression({
      algorithms: [
        // Development: faster builds, lower compression
        defineAlgorithm('gzip', { level: 6 }),
    
        // Production: slower builds, better compression
        defineAlgorithm('gzip', { level: 9 }),
    
        // Brotli: quality 10-11 recommended for static assets
        defineAlgorithm('brotliCompress', {
          params: {
            [require('zlib').constants.BROTLI_PARAM_QUALITY]: 11
          }
        })
      ]
    })