Git Product home page Git Product logo

vite-plugin-image-optimizer's Introduction

vite logo

Vite Image Optimizer

Plugin for Vite to optimize all images assets using Sharp.js and SVGO at build time.

node-current npm peer dependency version npm bundle size GitHub release licence

 

Features

  • Optimize SVG assets using SVGO and pass custom configs.
  • Optimize scalar assets (png, jpeg, gif, tiff, webp, avif) using Sharp.js with the option to pass custom configs for each extension type.
  • Option to process all assets from your public directory defined in the bundler.
  • Configure test, include, and exclude to filter assets.
  • Skip processing assets if their optimized size is greater than their original size.
  • Log the optimization stats showing the before and after size difference and ratio (optional)

Motivation

This plugin is based on the awesome image-minimizer-webpack-plugin for Webpack. I wanted to combine the optimization capabilities of Sharp.js and SVGO in a single package and I couldn't find a plugin for Vite that could accomplish this. I initially thought of adding squoosh and imagemin support as well but dropped the idea since they are no longer maintained.

If you find the plugin useful, consider showing your support by giving a ⭐

Contributions are most welcome! We follow conventional-commits

Installation

You can add it as a dev dependency to any of the package managers (NPM, Yarn, PNPM)

Supports Vite >=3 and Node >=14

npm install vite-plugin-image-optimizer --save-dev

Warning

sharp and svgo don't come installed as part of the package. You will have to install them manually and add it as a dev dependency. This is a design decision so you can choose to skip installing sharp if you only want to optimize svg assets using svgo and vice versa.

npm install sharp --save-dev
npm install svgo --save-dev

Usage

import { ViteImageOptimizer } from 'vite-plugin-image-optimizer';
import { defineConfig } from 'vite';

export default defineConfig(() => {
  return {
    plugins: [
      ViteImageOptimizer({
        /* pass your config */
      }),
    ],
  };
});

Default Configuration

The default configuration is made for lossless compression of image assets.

const DEFAULT_OPTIONS = {
  test: /\.(jpe?g|png|gif|tiff|webp|svg|avif)$/i,
  exclude: undefined,
  include: undefined,
  includePublic: true,
  logStats: true,
  svg: {
    multipass: true,
    plugins: [
      {
        name: 'preset-default',
        params: {
          overrides: {
            cleanupNumericValues: false,
            removeViewBox: false, // https://github.com/svg/svgo/issues/1128
          },
          cleanupIDs: {
            minify: false,
            remove: false,
          },
          convertPathData: false,
        },
      },
      'sortAttrs',
      {
        name: 'addAttributesToSVGElement',
        params: {
          attributes: [{ xmlns: 'http://www.w3.org/2000/svg' }],
        },
      },
    ],
  },
  png: {
    // https://sharp.pixelplumbing.com/api-output#png
    quality: 100,
  },
  jpeg: {
    // https://sharp.pixelplumbing.com/api-output#jpeg
    quality: 100,
  },
  jpg: {
    // https://sharp.pixelplumbing.com/api-output#jpeg
    quality: 100,
  },
  tiff: {
    // https://sharp.pixelplumbing.com/api-output#tiff
    quality: 100,
  },
  // gif does not support lossless compression
  // https://sharp.pixelplumbing.com/api-output#gif
  gif: {},
  webp: {
    // https://sharp.pixelplumbing.com/api-output#webp
    lossless: true,
  },
  avif: {
    // https://sharp.pixelplumbing.com/api-output#avif
    lossless: true,
  },
};

Plugin Options

test

Type: RegExp

Default: /\.(jpe?g|png|gif|tiff|webp|svg|avif)$/i

Test to match files against.

exclude

Type: String | RegExp | Array<string>

Default: undefined

Files to exclude.

include

Type: String | RegExp | Array<string>

Default: undefined

Files to include.

Warning

This will override any options set in test and exclude and has a higher preference. Use this option if you want to include specific assets only.

includePublic

Type: boolean

Default: true

Include all assets within the public directory defined in Vite. When true it will recursively traverse the directory and optimize all the assets.

logStats

Type: boolean

Default: true

Logs the optimization stats to terminal output with file size difference in kB and percent increase/decrease.

terminal output image

svg

Type: Object

Default:

{
  multipass: true,
  plugins: [
    {
      name: 'preset-default',
      params: {
        overrides: {
          cleanupNumericValues: false,
          removeViewBox: false, // https://github.com/svg/svgo/issues/1128
        },
        cleanupIDs: {
          minify: false,
          remove: false,
        },
        convertPathData: false,
      },
    },
    'sortAttrs',
    {
      name: 'addAttributesToSVGElement',
      params: {
        attributes: [{ xmlns: 'http://www.w3.org/2000/svg' }],
      },
    },
  ]
}

Config object to pass to SVGO, you can override it with your custom config.

png

Type: Object

Default:

{
  // https://sharp.pixelplumbing.com/api-output#png
  quality: 100,
}

Config object to pass to Sharp.js for assets with png extension

jpeg

Type: Object

Default:

{
  // https://sharp.pixelplumbing.com/api-output#jpeg
  quality: 100,
}

Config object to pass to Sharp.js for assets with jpg or jpeg extension

gif

Type: Object

Default:

{
  // https://sharp.pixelplumbing.com/api-output#gif
}

Config object to pass to Sharp.js for assets with gif extension

tiff

Type: Object

Default:

{
  // https://sharp.pixelplumbing.com/api-output#tiff
  quality: 100,
}

Config object to pass to Sharp.js for assets with tiff extension

webp

Type: Object

Default:

{
  // https://sharp.pixelplumbing.com/api-output#webp
  lossless: true,
}

Config object to pass to Sharp.js for assets with webp extension

avif

Type: Object

Default:

{
  // https://sharp.pixelplumbing.com/api-output#avif
  lossless: true,
}

Config object to pass to Sharp.js for assets with avif extension

License

MIT

vite-plugin-image-optimizer's People

Contributors

fatehak avatar renovate[bot] avatar mfjordvald avatar dmkelly avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.