vite-plugin-image-optimizer

repository·main·Indexed 19 days ago

https://github.com/fatehak/vite-plugin-image-optimizer

A Vite plugin that automates the optimization of image assets (SVG, PNG, JPEG, GIF, TIFF, WebP, AVIF) during the build process using Sharp.js and SVGO. It supports custom configuration for each image format, asset filtering via include/exclude patterns, caching for faster builds, and optimization of assets within the Vite public directory.

Tokens
2.4K
Snippets
5
Records
11
Agent score
66%

What's inside vite-plugin-image-optimizer

  1. Install vite-plugin-image-optimizer

    main

    Install the plugin as a dev dependency using your preferred package manager.

    Important: This plugin does not include sharp or svgo by default. You must install them manually as dev dependencies. This allows you to choose whether you want to optimize only SVGs (install svgo) or only raster images (install sharp).

    npm install vite-plugin-image-optimizer --save-dev
    
    # Manually install required engines
    npm install sharp --save-dev
    npm install svgo --save-dev
  2. Enable caching for faster builds

    main

    To avoid re-optimizing assets in consecutive builds, you can enable caching.

    • cache: A boolean to enable or disable caching (default: false).
    • cacheLocation: A String specifying the path to the cache directory. This is useful for CI/CD environments like GitHub Actions to speed up builds.
  3. Configure logging and terminal output

    main

    Control how optimization statistics are displayed in your terminal:

    • logStats: A boolean (default: true) that logs optimization stats including file size difference (kB), percentage change, and total savings.
    • ansiColors: A boolean (default: true) that enables/disables ANSI colors in the terminal output. Set to false if your shell does not support color text.
  4. Configure asset filtering with test, include, and exclude

    main

    You can control which files are processed using these three options:

    • test: A RegExp used to match files against. Default is /\.(jpe?g|png|gif|tiff|webp|svg|avif)$/i.
    • exclude: A String, RegExp, or Array<string> of files to skip. Using a RegExp allows you to exclude specific folders (e.g., exclude: /textures/).
    • include: A String, RegExp, or Array<string> of files to process.

    Note: include has higher precedence than test and exclude and will override them if provided.

  5. Configure raster image optimization with Sharp.js

    main

    You can pass custom configuration objects to Sharp.js for different image formats using the following keys:

    • png: Accepts PngOptions.
    • jpeg / jpg: Accepts JpegOptions.
    • gif: Accepts GifOptions.
    • tiff: Accepts TiffOptions.
    • webp: Accepts WebpOptions.
    • avif: Accepts AvifOptions.

    Example for setting quality:

    { 
      png: { quality: 100 },
      webp: { lossless: true }
    }
  6. Configure SVG optimization with the svg option

    main

    The svg option accepts an SVGOConfig object to pass custom settings to SVGO.

    Default configuration:

    {
      multipass: true,
      plugins: [
        {
          name: 'preset-default',
          params: {
            overrides: {
              cleanupNumericValues: false,
              removeViewBox: false,
              cleanupIDs: {
                minify: false,
                remove: false,
              },
              convertPathData: false,
            },
          },
        },
        'sortAttrs',
        {
          name: 'addAttributesToSVGElement',
          params: {
            attributes: [{ xmlns: 'http://www.w3.org/2000/svg' }],
          },
        },
      ]
    }
  7. Use ViteImageOptimizer in Vite

    main

    Import ViteImageOptimizer from vite-plugin-image-optimizer and add it to the plugins array in your vite.config.js or vite.config.ts file.

    import { ViteImageOptimizer } from 'vite-plugin-image-optimizer';
    import { defineConfig } from 'vite';
    
    export default defineConfig(() => {
      return {
        plugins: [
          ViteImageOptimizer({
            /* pass your config */
          }),
        ],
      };
    });
  8. Default configuration for vite-plugin-image-optimizer

    main

    When no options are provided, the plugin uses the following default configuration. This includes settings for file inclusion/exclusion, logging, and format-specific optimization parameters (using sharp and svgo).

    File Matching

    • test: Matches files with extensions jpe?g, png, gif, tiff, webp, svg, or avif (case-insensitive).
    • include: Defaults to undefined (all files matching test are processed).
    • exclude: Defaults to undefined (no files are excluded).
    • includePublic: Defaults to true.

    Optimization Defaults

    • SVG: Uses svgo with multipass: true and a preset that disables certain cleanups (like cleanupNumericValues and convertPathData) to preserve data integrity, while adding the xmlns attribute.
    • PNG/JPEG/JPG/TIFF: Default quality is 100.
    • WebP/AVIF: Default to lossless: true.
    • GIF: Uses empty options (lossless compression is not supported for GIF).

    General Settings

    • logStats: true (logs optimization results to the console).
    • ansiColors: true (enables colored console output).
    • cache: false.
    • cacheLocation: undefined.
    // Example of how the default structure looks for configuration
    {
      logStats: true,
      ansiColors: true,
      includePublic: true,
      exclude: undefined,
      include: undefined,
      test: /\.(jpe?g|png|gif|tiff|webp|svg|avif)$/i,
      svg: { /* SVGO config */ },
      png: { quality: 100 },
      jpeg: { quality: 100 },
      jpg: { quality: 100 },
      tiff: { quality: 100 },
      gif: {},
      webp: { lossless: true },
      avif: { lossless: true },
      cache: false,
      cacheLocation: undefined
    }
  9. Configure ViteImageOptimizer options

    main

    The ViteImageOptimizer accepts an Options object to control file matching, optimization engines, and caching behavior.

    File Matching

    • test: A RegExp to match files against.
    • include: A RegExp, string, or string[] to explicitly include files. This has higher priority than test and exclude.
    • exclude: A RegExp, string, or string[] to exclude files.
    • includePublic: A boolean that, if true, also optimizes assets found in the Vite public directory.

    Optimization Engine Settings

    Options are passed directly to the underlying engines:

    • svg: Configuration for svgo.
    • png: Configuration for sharp (PNG).
    • jpeg / jpg: Configuration for sharp (JPEG).
    • tiff: Configuration for sharp (TIFF).
    • gif: Configuration for sharp (GIF).
    • webp: Configuration for sharp (WebP).
    • avif: Configuration for sharp (AVIF).

    Caching and Logging

    • cache: A boolean to enable/disable caching of optimized images.
    • cacheLocation: A string specifying the directory where optimized images are stored.
    • logStats: A boolean to display optimization statistics in the terminal.
    • ansiColors: A boolean to enable/disable colored logs in the terminal.
    import { defineConfig } from 'vite';
    import { ViteImageOptimizer } from 'vite-plugin-image-optimizer';
    
    export default defineConfig({
      plugins: [
        ViteImageOptimizer({
          test: /.(png|jpe?g|tiff|gif|webp|avif|svg)$/, // Match specific extensions
          includePublic: true,                          // Also optimize files in /public
          cache: true,                                  // Enable caching
          cacheLocation: './.image-cache',             // Custom cache directory
          logStats: true,                               // Show stats in terminal
          svg: {                                        // SVGO specific options
            multipass: true,
          },
          jpg: {                                        // Sharp specific options
            quality: 80,
          },
        }),
      ],
    });
  10. Initialize ViteImageOptimizer plugin

    main

    To use the plugin, call ViteImageOptimizer() within your vite.config.ts file. It is a Vite plugin that optimizes images (SVG, PNG, JPEG, JPG, TIFF, GIF, WebP, AVIF) during the build process using svgo and sharp. By default, it only applies during the build phase and enforces post order.

    import { defineConfig } from 'vite';
    import { ViteImageOptimizer } from 'vite-plugin-image-optimizer';
    
    export default defineConfig({
      plugins: [
        ViteImageOptimizer(),
      ],
    });