Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

vite-plugin-compression2

nonzzz394.1kMIT2.2.0TypeScript support: included

a fast vite compression plugin

vite, vite-plugin, compress

readme

codecov

Install

$ yarn add vite-plugin-compression2 -D

# or

$ npm install vite-plugin-compression2 -D

Usage

Basic Usage

import { defineConfig } from 'vite'
import { compression } from 'vite-plugin-compression2'

export default defineConfig({
  plugins: [
    // ...your plugins
    compression()
  ]
})

Multiple Algorithms

import { compression, defineAlgorithm } from 'vite-plugin-compression2'

export default defineConfig({
  plugins: [
    compression({
      algorithms: [
        'gzip',
        'brotliCompress',
        defineAlgorithm('deflate', { level: 9 })
      ]
    })
  ]
})

Custom Algorithm Function

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 }
        )
      ]
    })
  ]
})

With Tarball

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' })
  ]
})

Options

Compression Plugin Options

params type default description
include string | RegExp | Array<string | RegExp> /\.(html|xml|css|json|js|mjs|svg|yaml|yml|toml)$/ Include all assets matching any of these conditions.
exclude string | RegExp | Array<string | RegExp> - Exclude all assets matching any of these conditions.
threshold number 0 Only assets bigger than this size are processed (in bytes)
algorithms Algorithms ['gzip', 'brotliCompress'] Array of compression algorithms or defineAlgorithm results
filename string | function [path][base].gz or [path][base]. br If algorithm is zstd be [path][base].zst The target asset filename pattern
deleteOriginalAssets boolean false Whether to delete the original assets or not
skipIfLargerOrEqual boolean true Whether to skip the compression if the result is larger than or equal to the original file

Tarball Plugin Options

params type default description
dest string - Destination directory for tarball

API

defineAlgorithm(algorithm, options?)

Define a compression algorithm with options.

Parameters:

  • algorithm: Algorithm name ('gzip' | 'brotliCompress' | 'deflate' | 'deflateRaw' | 'zstandard') or custom function
  • options: Compression options for the algorithm

Returns: [algorithm, options] tuple

Examples:

// 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' }
)

Supported Algorithms

Algorithm Aliases Extension Node.js Support Description
gzip gz .gz All versions Standard gzip compression with good balance of speed and ratio
brotliCompress brotli, br .br All versions Brotli compression with better compression ratio than gzip
deflate - .gz All versions Deflate compression algorithm
deflateRaw - .gz All versions Raw deflate compression without headers
zstandard zstd .zst >= 22.15.0 or >= 23.8.0 Zstandard compression with excellent speed/ratio balance
Custom Function - Custom All versions Your own compression algorithm implementation

Algorithm Types

The algorithms option accepts:

type Algorithms =
  | Algorithm[] // ['gzip', 'brotliCompress']
  | DefineAlgorithmResult[] // [defineAlgorithm('gzip'), ...]
  | (Algorithm | DefineAlgorithmResult)[] // Mixed array

Migration

If you're upgrading from v1.x, please check the Migration Guide.

Q & A

FAQ

Examples

Basic Gzip Only

compression({
  algorithms: ['gzip']
})

Multiple Algorithms with Custom Options

compression({
  algorithms: [
    defineAlgorithm('gzip', { level: 9 }),
    defineAlgorithm('brotliCompress', {
      params: {
        [require('zlib').constants.BROTLI_PARAM_QUALITY]: 11
      }
    })
  ]
})

Custom Filename Pattern

compression({
  algorithms: ['gzip'],
  filename: '[path][base].[hash].gz'
})

Delete Original Files

compression({
  algorithms: ['gzip'],
  deleteOriginalAssets: true
})

Size Threshold

compression({
  algorithms: ['gzip'],
  threshold: 1000 // Only compress files larger than 1KB
})

Others

  • If you want to analyze your bundle assets, try vite-bundle-analyzer
  • tarball option dest means to generate a tarball somewhere
  • tarball is based on the ustar format. It should be compatible with all popular tar distributions (gnutar, bsdtar etc)

Node.js Version Requirements

  • gzip, brotliCompress, deflate, deflateRaw: All Node.js versions supported
  • zstd: Requires Node.js >= 22.15.0 or >= 23.8.0

Note: If you try to use zstd compression on an unsupported Node.js version, the plugin will throw a helpful error message indicating the required version.

Sponsors

LICENSE

MIT

Acknowledgements

NWYLZW

Author

Kanno

changelog

2.2.0

  • Add compression algorithm aliases.
  • The correct variable should be passed when using custom filename.

Credits

@solonovamax

2.1.0

  • Add zstd support. (Use the built-in zstd of nodejs. Note that you need to ensure your local node version)

2.0.1

  • Fix build script.

2.0.0

Major Changes

  • Changed algorithm option to algorithms (array support)
  • Removed compressionOptions in favor of new defineAlgorithm() helper
  • Enhanced API for better developer experience

New Features

  • Support for multiple compression algorithms in a single plugin instance
  • New defineAlgorithm() helper for better type-safety and options control
  • Custom compression algorithm support via function callbacks

Improvements

  • Better TypeScript type definitions
  • Simplified configuration for common use cases
  • Added comprehensive migration guide
  • Added Q&A document for common usage patterns

See the Migration Guide for detailed upgrade instructions.

1.4.0

Added build log output for compression result.

This enhancement provides visibility into compression results during the build process, complementing Vite's default reporter by including assets from the public directory in the output statistics.

1.3.3

Patches

  • Fix error deps

1.3.2

Support Vite6

1.3.1

Using jiek

1.3.0

Improves

  • tarball support generate gz archive.

Patches

  • Fix vite@2 can't work.

1.2.0

  • Support work with plugins that specify hook order.

1.1.4

  • Migrate to tar-mini

1.1.3

Improves

  • Option include add more defaults.

Patches

  • Fix overload error.

Credits

@mengdaoshizhongxinyang @silverwind

1.1.2

Improve

  • Remove tar-stream.

1.1.1

Patches

  • Tarball should handle right static sources.

1.1.0

Improve

  • Option include add default value.

Credits

@Ibadichan

1.0.0

Background

This is a stable version.

Major

  • Rename plugin cp as tarball and remove unnecessary options.

Improves

  • Optimize compression task.

0.12.0

Background

Improves

  • expose new plugin cp.(a tarball helper)

0.11.0

Background

  • Details see #41

0.10.6

Background

Improves

  • Perf types.
  • Reduce unnecessary installation packages.

0.10.5

Background

Improves

  • Reduce bundle size.

Patches

  • Fix can't work at monorepo.

0.10.4

Background

  • Make options happy

0.10.3

Background

Patches

  • Fix output option duplicate. #39

0.10.2

Background

Patches

  • Fix option filename called result same as bundle filename can't work. #31

0.10.1

Background

Patches

  • Fix chunk with side effect can't work with threshold #33

0.10.0

Background

Improve & Features

  • Add skipIfLargerOrEqual option. #32

Credits

@vHeemstra @nonzzz

0.9.3

Background

Improve

  • Static Directory support size check.

0.9.2

Background

Patches

  • Fix filename same as bundle source name can't work. #30

Credits

@jglee96 @nonzzz

0.9.1

Background

Improve

  • Reduce unnecessary io (Currently, We don't handle viteMetaData.Becasue vite has already process them)
  • Add queue to optimize task processing.

Patches

  • Fix that the file with side effect can't be filterd.
  • Static assets can't handle correctly.

0.9.0

Background

  • Support multiple process. #27

0.8.4

Background

Patches

  • Fix filter can't work with dynamic source. #25

0.8.3

Background

  • Reduce bundle size.
  • Perf ReadAll func.

0.8.2

Background

Patches

  • Fix nesting public assets can't work normal. #23

0.8.1

Background

Patches

  • Fix public assets can't work with filter

0.8.0

Background

Improves & Features

  • Support compress public resource. #22

0.7.0

Background

Improves & Features

  • Remove hook order #20
  • Remove peerDependencies

0.6.3

Background

Patches

  • Fix type error (#16)

Credits

@ModyQyW

0.6.2

Background

  • Fix bundle error

0.6.1

Background

Improves & Features

  • Perf function type. (Details see #12)
  • Add named exports.(Some user prefer like their project is full esm. #14)

Credits

@MZ-Dlovely @ModyQyW

0.6.0

Background

Improves & Features

  • Algorithm will using gzip If user pass a error union type.
  • Update document usage.

0.5.0

Background

MINOR

  • Migrate vite version.
  • Peerdependencies support vite3 and vite.

0.4.3

Background

Patches

  • Fix dynamicImports loose right assets info.(Vite's intenral logic cause it. So we define the order for us plugin).

0.4.2

Background

Minor

  • Perf chunk collect logic. In collect setp. Don't clone a new buffer data.
  • Change release file. using .mjs,.js.

Others

  • Update project dependencies.

0.4.1

Background

Patches

  • Fix dynamicImports can't generator right compressed file.

0.4.0

Background

Improves & Features

  • Add filename prop.(Control the generator source name)
  • Enhanced type inference.
  • Performance optimization.