Giter Club home page Giter Club logo

vite-plugin-compress's Introduction

vite-plugin-compress

npm Code style: Prettier Donate

Compress your bundle + assets from Vite

  • Assets generated by Vite and assets from ./public are compressed with Brotli
  • Images, sounds, WOFF2 fonts, and PDFs are not compressed with Brotli, since these formats are compressed by default
  • SVGs are further optimized with svgo
  • PNGs are further optimized with imagemin
  • By default, files smaller than 1501 bytes are not compressed, since the MTU of a TCP packet is 1500 bytes
  • Compatible with vite-ssr
    • Just add exclude: ["ssr-manifest.json"]

 

Usage

import compress from 'vite-plugin-compress'

export default {
  plugins: [
    compress(),
  ]
}

Options

  • quality: number
    Higher quality means smaller file sizes.
    Defaults to max quality (11).

  • threshold: number
    Minimum file size (in bytes) to be compressed.
    Defaults to 1501.

  • exclude: string[]
    Globs to exclude certain files from being compressed.

  • extensions: string[]
    Additional extensions to compress with Brotli.

    Default extensions include:

    • .html
    • .js
    • .css
    • .svg
    • .json
  • svgo: object
    Options for the SVG optimizer.
    More info here.

    Default plugins include:

    • removeViewBox: false
    • removeDimensions: true
    • Plugins listed here are enabled
  • pngquant: object
    Options for the PNG optimizer.
    More info here.

  • brotli: boolean
    Set to false to disable Brotli compression.

  • verbose: boolean
    Log compressed files and their compression ratios.

vite-plugin-compress's People

Contributors

aleclarson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

vite-plugin-compress's Issues

Project cannot be built

Running yarn build results in

src/plugin.ts:138:14 - error TS2551: Property 'resolveBuiltUrl' does not exist on type 'Plugin'. Did you mean 'resolveFileUrl'?

138         this.resolveBuiltUrl = url => {
                 ~~~~~~~~~~~~~~~

src/plugin.ts:138:32 - error TS7006: Parameter 'url' implicitly has an 'any' type.

138         this.resolveBuiltUrl = url => {
                                   ~~~

src/plugin.ts:168:55 - error TS2571: Object is of type 'unknown'.

168               debug(`Failed to transform "${id}". ` + err.message)
                                                          ~~~

The Object is of type 'unknown' is related to TypeScript 4.4 and easy to fix but what is resolveBuiltUrl supposed to do? It looks like dead code

set deleteOriginFile true and get wrong

vite3.0 + vue3
compressPlugin({
      deleteOriginFile: true,
      algorithm: 'gzip'
 })

I set the option of deleteOriginFile as true ,then run build,get wrong,like it
image

how can the files be served with the correct content-encoding?

I'm probably completely lost, but... using vite-plugin-compress on a vite/vue2 project I end up with compressed files in dist/assets that all have the plain file extensions, e.g. .js, .css, etc. But as far as I understand these files need to be served with a content-encoding: br header? How is my static file web server supposed to know which of the .js files are compressed and which are not? I was expecting to see a .br filename extension or something like that...

viteCompress is not a function

I have the basic setup that the README documents;

import viteCompress from 'vite-plugin-compress'
...
export default defineConfig(({ command }) => ({
  ...
  plugins: [
    viteCompress(),
  ]
  ...
}

But I get the following error:

failed to load config from /var/www/html/config/build/vite.config.ts
error during build:
TypeError: viteCompress is not a function

clean build fails on latest version of Vite

Steps to reproduce

  • git clone into a fresh directory
  • Install dependencies
  • Run pnpm run build in project root and then in demo/

Error

[vite:compress] setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.
file: /home/hydrocodone/Repositories/vite-plugin-compress/demo/public/test.svg
error during build:
Error: setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.
    at error (/home/hydrocodone/Repositories/vite-plugin-compress/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:5305:30)
    at throwPluginError (/home/hydrocodone/Repositories/vite-plugin-compress/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:18040:12)
    at Object.error (/home/hydrocodone/Repositories/vite-plugin-compress/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:18666:20)
    at Object.error (/home/hydrocodone/Repositories/vite-plugin-compress/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:18209:38)
    at Object.setAssetSource (/home/hydrocodone/Repositories/vite-plugin-compress/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:18228:29)
    at Object.transform (/home/hydrocodone/Repositories/vite-plugin-compress/dist/plugin.js:107:34)
    at async ModuleLoader.addModuleSource (/home/hydrocodone/Repositories/vite-plugin-compress/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:18403:30)
    at async ModuleLoader.fetchModule (/home/hydrocodone/Repositories/vite-plugin-compress/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:18459:9)
    at async Promise.all (index 1)
    at async ModuleLoader.fetchStaticDependencies (/home/hydrocodone/Repositories/vite-plugin-compress/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/shared/rollup.js:18485:34)
 ERROR  Command failed with exit code 1.

This could be caused by recent breaking change in Vite v2.3.0. Will submit PR for review.

Support a suffix for compressed files

In our use case the server would want to know if a file is compressed or not so that it can serve the file in a way that the browser understands. One way of accomplishing this would be to add a outputSuffix parameter that, when set, would write the compressed version as filename+outputSuffix instead of overwriting the original file.

If this makes sense, I could create a PR once #11 is resolved somehow

Failed to compress svg's

I got this error while trying this plugin. Any idea how to exclude svg's ? I tried : compress({ exclude: ["*.svg"] })

✓ 560 modules transformed.
[vite:compress] setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.
file: F:/GitHub/senf/apps/senf-client/src/images/svgIcons/plus.svg
error during build:
Error: setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook. at error (F:\GitHub\senf\apps\senf-client\node_modules\rollup\dist\shared\rollup.js:198:30)
at throwPluginError (F:\GitHub\senf\apps\senf-client\node_modules\rollup\dist\shared\rollup.js:21847:12)
at Object.error (F:\GitHub\senf\apps\senf-client\node_modules\rollup\dist\shared\rollup.js:22570:20)
at Object.error (F:\GitHub\senf\apps\senf-client\node_modules\rollup\dist\shared\rollup.js:22024:42)
at Object.setAssetSource (F:\GitHub\senf\apps\senf-client\node_modules\rollup\dist\shared\rollup.js:22043:33)
at Object.transform (F:\GitHub\senf\apps\senf-client\node_modules\vite-plugin-compress\dist\plugin.js:107:34)
at async transform (F:\GitHub\senf\apps\senf-client\node_modules\rollup\dist\shared\rollup.js:21994:16)
at async ModuleLoader.addModuleSource (F:\GitHub\senf\apps\senf-client\node_modules\rollup\dist\shared\rollup.js:22220:30)

source code looks like this:
import Plus from "../../../images/svgIcons/plus.svg";
<img src={Plus} width="25" alt="AddIcon" />

it‘s no effect

befor use this plugin
image
after
image
the .jpg file didn't compressed at all.

install error

error D:\project\node_modules\pngquant-bin: Command failed.
Exit code: 1
Command: node lib/install.js
Arguments:
Directory: D:\project\node_modules\pngquant-bin
Output:
‼ getaddrinfo ENOENT raw.githubusercontent.com
  ‼ pngquant pre-build test failed
  i compiling from source
  × Error: pngquant failed to build, make sure that libpng-dev is installed
    at D:\workspace\jojoread-medal-fe\node_modules\execa\index.js:231:11

Move heavy dependencies to peerDependencies

Heavy dependencies include:

  • html-minifier-terser (in next branch only)
  • imagemin-pngquant
  • imagemin-webp (in next branch only)
  • svgo

All of these take ~5 MB each.

Benefits:

  • Less wasted space when not using a specific feature
  • Faster installation

Drawbacks:

  • More burdensome setup/maintenance
  • A few wasted MB isn't the end of the world
  • Their dependencies may overlap, so the "5 MB" figure could be overstated

cause unicode problem

i use the vite2.6.13 and vite-plugin-vue2,1.9.0,the files parsed unicode problem,and cannot correctly display
then output all the file just like this:
�4�ŒÔV7„‰«î§î§•œõž@º�¿ÕaÑ9å´�y�K+��«†ÎÙ��¡ben÷.µÓƧ(&Žò�ªzU(�� Ñ�íP1gÛŽž� [rJ��Vð’��ƒk]/ó��r(ˆŸ!¢ÈJQì•ÿo#Áô�0ßUM5¾û™9�wU¬˜éØ*‰ 7”#!Z²�¹™�»I��^£Ô¤$¨yc�ëH¶6œ¤y7 Û�¢eæ�«êj�:÷ëåö¹obSH;W{O£Õ…�P;bAHGQb]€�0—µ k45�X…!Å_�ihTQ¥0�’Í�õ&�'Y�+\°�L°Ú ɾ-1ðþ/NGõ8’|ú±×zøEÙ2MÒ²Œfe��ßO~�¤¹Ó»Ç‹é&œgp� °'Ğg�´Æë�_;#9º�.Æìº÷4�­F�£w®(×qh<ãøƒ�/�¼©}°/îým˜m‡ruoëH �"ƒ;”¥ªŠ0V�==hïC€’‘êPc…é½L�­IÖôé1„®«RÛ#©�9�PÕ©�žc�ÊÀê-кj€ø‘dãqÕ+ÆÏÇ4 ‹ÔÂ�PŠÄ²§cvÄM¾È�æô3×4p$Zëœp&^,{†±VÖT24oW?e=œú¸^ïh{¡='Eë)�¯;ãDõÈê•yéö…Ø{ám*¶�Ø3–aq­ZÇ…���}«hš®¶ å‚Ù1Hi¶X:•í=³ÂgT�¥Þe‹�ÿ= c�“Þ�ÖÈ�¸®�Û»ÃbÉž…Ç�,Û,`��HøÛl‚xA3º�†�‡¤�Ÿ'|í7C:k�KŒñÈ&ˆ�t�Aë�÷�½+Z «CÅæ�ßëx,Y¶?â�e�¡ôš�òn ·±�IZá|µ,û8¼ò�! �7.D�Ge€BͫֆݪÓñt3�ÇĦû—��§=”�Q[.YÓtRÏÆuôïà�Àn�¯îa§²Ÿ

Can't build with vite@4, Is it really abandoned?

This plugin is really broken with vite@4. Just, create a vite project based on one of the available templates, then use this plugin as documented in readme. I even tried it as a regular dependency and again as a dev dependency but failed.

problem 1:

failed to load config from /home/linuxuser/my-vue-app/vite.config.js
error during build:
TypeError: compress is not a function
    at file:///home/linuxuser/my-vue-app/vite.config.js.timestamp-1689109439253-f0f6a29d5d51b.mjs:8:5
    at ModuleJob.run (node:internal/modules/esm/module_job:192:25)

problem 2 - compress.default() instead of compress() didn't help at all, and I'm receiving this error:

error during build:
TypeError: Cannot set properties of undefined (setting 'writeBundle')
    at configResolved (/home/linuxuser/my-vue-app/node_modules/vite-plugin-compress/dist/plugin.js:39:30)
    at file:///home/linuxuser/my-vue-app/node_modules/vite/dist/node/chunks/dep-210e5610.js:65822:28
    at Array.map (<anonymous>)
    at resolveConfig (file:///home/linuxuser/my-vue-app/node_modules/vite/dist/node/chunks/dep-210e5610.js:65822:14)
    at async build (file:///home/linuxuser/my-vue-app/node_modules/vite/dist/node/chunks/dep-210e5610.js:47747:20)
    at async CAC.<anonymous> (file:///home/linuxuser/my-vue-app/node_modules/vite/dist/node/cli.js:822:9)

Please, archive this repository if it's really abandoned

Fix security Denial of Service issues

Steps for Reproduction:

  1. npm install vite-plugin-compress
  2. npm audit

Expected behavior:

No security advisory.

Actual behavior:

┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High          │ Regular Expression Denial of Service                         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ trim-newlines                                                │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=3.0.1 <4.0.0 || >=4.0.1                                    │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ vite-plugin-compress [dev]                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ vite-plugin-compress > imagemin-pngquant > pngquant-bin >    │
│               │ logalot > squeak > lpad-align > meow > trim-newlines         │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://npmjs.com/advisories/1753                            │
└───────────────┴──────────────────────────────────────────────────────────────┘
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High          │ Denial of Service                                            │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package       │ css-what                                                     │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Patched in    │ >=5.0.1                                                      │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ vite-plugin-compress [dev]                                   │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path          │ vite-plugin-compress > svgo > css-select > css-what          │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info     │ https://npmjs.com/advisories/1754                            │
└───────────────┴──────────────────────────────────────────────────────────────┘

Platforms:

N/A

Version:

2.1.0

ENOENT: no such file or directory

I am using a simple vite.config.ts like this:

import type { UserConfig } from 'vite';
import { resolve } from "path";
import vue from '@vitejs/plugin-vue';
import compress from 'vite-plugin-compress'

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir);
}

export default {
    plugins: [
        vue(),
        compress()
    ],
    resolve: {
        alias: {
            "/@": pathResolve('src') + '/',
            'vue': 'vue/dist/vue.esm-bundler.js' // 定义vue的别名,如果使用其他的插件,可能会用到别名
        },
        dedupe: ['vue'],
    },
}

after npm run build, I got the following error:

[vite:compress] ENOENT: no such file or directory, open '/404.svg'
file: /404.svg
error during build:
Error: ENOENT: no such file or directory, open '/404.svg'

404.svg is exactly exist , just under /public.

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.