Git Product home page Git Product logo

vite-plugin-compression's Introduction

Hi there 👋

  • You can call me Kanno
  • I've been busy recently
  • Learning zig

vite-plugin-compression's People

Contributors

ibadichan avatar jglee96 avatar mengdaoshizhongxinyang avatar modyqyw avatar mz-dlovely avatar nonzzz avatar silverwind avatar vheemstra avatar yell0wsuit 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

vite-plugin-compression's Issues

public子目录嵌套生成错误

最新的0.8.1中,我的public目录是这样的:
public/textures/hdr/blouberg_sunrise_2_1k.hdr

但是最后的dist文件中不会生成br或者gz文件。

经调试发现问题出现在以下函数(utils.ts)中:

// [path][base].ext
export function replaceFileName(staticPath: string, rule: string | ((id: string) => string)) {
    const series = staticPath.split('/')
    const base = series.pop()
    const fileNameTempalte = typeof rule === 'function' ? rule(staticPath) : rule
    let path = series.filter((_, idx) => idx === len(series) - 1).join('/')
    if (len(path)) path = path + '/'

    console.log('staticPath', staticPath)
    console.log('series ', series)
    console.log('path ' + path)
    const ret = fileNameTempalte.replace(/\[path\]/, path).replace(/\[base\]/, base)

    console.log('final: ' + ret);
}

打印后出现:

staticPath textures/hdr/blouberg_sunrise_2_1k.hdr
series  [
  'textures',
  'hdr'
]
path hdr/
final: hdr/blouberg_sunrise_2_1k.hdr.br

最后的值不正确,应该是textures/hdr/blouberg_sunrise_2_1k.hdr.br才对

这个replace函数好像在其他地方也用了,不确定怎么修改,故保险起见还是提个issue吧 :)

Plugin Runs Before Processes Finish

Hi,

After finishing the Vite operations, I minify the JSON files myself, but I cannot read the content of the JSON file because this plugin was working before.

打包后,生产环境中css样式不生效

打包后,生产环境中css样式不生效

 compression({ deleteOriginalAssets: true, include: [/\.(js)$/, /\.(css)$/, /\.(mjs)$/, /\.(json)$/] }),

当我使用vite-plugin-compression时,样式是正常的 我不确定具体是什么导致这个问题的产生

构建完成后控制台输出信息报告缺失

Bug report 🐞

Version & Environment

  plugins: [
    compression({
      threshold: 1024,
      include: /\.(js|mjs|json|css|html|wasm)$/i,
    }),
    compression({
      algorithm: "brotliCompress",
      threshold: 1024,
      include: /\.(js|mjs|json|css|html|wasm)$/i,
      exclude: /\.(br|gz)$/i,
    })
  ]
{
  "dependencies": {
    "@jsquash/png": "^2.0.0",
    "@jsquash/webp": "^1.1.3",
    "axios": "^1.1.3",
    "pinia": "^2.0.17",
    "vfonts": "^0.0.3",
    "vue": "^3.2.37",
    "vue-router": "^4.1.3"
  },
  "devDependencies": {
    "@rushstack/eslint-patch": "^1.1.4",
    "@vitejs/plugin-vue": "^4.0.0",
    "@vitejs/plugin-vue-jsx": "^3.0.0",
    "@vue/eslint-config-prettier": "^7.0.0",
    "eslint": "^8.23.0",
    "eslint-plugin-vue": "^9.4.0",
    "naive-ui": "^2.33.5",
    "prettier": "^2.7.1",
    "vite": "^4.1.4",
    "vite-plugin-cdn-import-rely": "^3.1.0",
    "vite-plugin-compression2": "^0.8.2",
    "vite-plugin-dynamic-import": "^1.2.3",
    "vite-plugin-remove-console": "^2.1.0",
    "vite-plugin-windicss": "^1.8.8",
    "windicss": "^3.5.6"
  }
}

Expection

image

Actual results (or Errors)

image
只有第一层文件夹的 .gz.br 文件输出到控制台了,但实际上所有文件都正确输出压缩文件到 dist/ 目录下了。

安装失败了,是不兼容vite4.0.4吗?

Bug report 🐞

Version & Environment

Expection

Actual results (or Errors)

# npm resolution error report

While resolving: [email protected]
Found: [email protected]
node_modules/vite
  dev vite@"^4.0.3" from the root project

Could not resolve dependency:
peer vite@"^3.2.3" from [email protected]
node_modules/vite-plugin-compression2
  dev vite-plugin-compression2@"*" from the root project

Fix the upstream dependency conflict, or retry
this command with --force or --legacy-peer-deps
to accept an incorrect (and potentially broken) dependency resolution.

Feature: Should handle multiple output

Feature request 🚀

Expected:

Vite set multiple output should be support.
see #26. If user pass the rollupOptions. the preset outDir won't be work. So what about passing in multiple outputs?

Examples:

export default defineConfig({
 build: {
    rollupOptions: {
      output: [{ dir: 'es' }, { dir: 'cjs' }]
    }
  },
})

This plugin swallowing actual build errors

Bug report 🐞

Added the plugin as

compression({
	include: [/\.(js)$/],
	deleteOriginalAssets: true,
	algorithm: 'brotliCompress',
	filename: '[path][base].br',
}),

If any build error happens, this plugin seems to be taking it and printing a generic error:

node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[Error: ENOENT: no such file or directory, open 'dist/assets/index.js'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'dist/assets/index.js'
}

Version & Environment

vite: "4.1.4"
vite-plugin-compression2: "0.9.2"

我在vuepress中使用遇到了一些问题

Bug report 🐞

我想要压缩 vuepress 生成的静态资源,参考 https://v2.vuepress.vuejs.org/zh/reference/bundler/vite.html 配置

pnpm add -D vite-plugin-compression2
import { defineUserConfig, viteBundler } from "vuepress";
import { compression } from "vite-plugin-compression2";

export default defineUserConfig({
  bundler: viteBundler({
    viteOptions: {
      plugins: [
        compression(),
      ],
    },
  }),
});

也尝试使用,但错误都一样

import { defineUserConfig, viteBundler } from "vuepress";
import { compression } from "vite-plugin-compression2";

export default defineUserConfig({
  bundler: viteBundler({
    viteOptions: {
      plugins: [
        compression({
          include: [/\.(js|mjs|json|css|html)$/],
          exclude: [/\.(br)$/, /\.(gz)$/],
          algorithm: "brotliCompress",
        }),
      ],
    },
  }),
});

Version & Environment

  • pnpm
  • vuepress 2.0.0-beta.60 (vite 4.0.4)
  • vite-plugin-compression2: 0.6.3

Expection

Actual results (or Errors)

构建过程报错

⠹ Compiling with vite[vite-plugin-compression] Cannot read properties of undefined (reading 'type')
✖ Compiling with vite - failed in 50.23s
TypeError: Cannot read properties of undefined (reading 'type')
    at file:///D:/Users/mc/Documents/GitHub/www.u2sb.com/node_modules/.pnpm/[email protected]/node_modules/vite-plugin-compression2/dist/index.mjs:106:47
    at Array.map (<anonymous>)
    at Object.handler (file:///D:/Users/mc/Documents/GitHub/www.u2sb.com/node_modules/.pnpm/[email protected]/node_modules/vite-plugin-compression2/dist/index.mjs:103:70)     
    at file:///D:/Users/mc/Documents/GitHub/www.u2sb.com/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/rollup.js:23704:40
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
 ELIFECYCLE  Command failed with exit code 1.

但是尝试使用 https://github.com/vbenjs/vite-plugin-compression 是可以正常构建并压缩的。

opts 应该是可选的

Bug report 🐞

opts 应该是可选的,可以通过文档和代码确认这一点。

image

image

Version & Environment

  • vite-plugin-compression2: v0.6.2
  • node: 18.13.0
  • yarn: 1.22.19
  • typescript: 4.9.5

Expection

opts 应该是可选的。

Actual results (or Errors)

出现类型错误,必须传入 opts。

image

类型文件中 opts 变成了必选。

image

[tarball] robots.txt from public folder is not bundled

Bug report 🐞

Hi! I was just trying to use this component, but I found a small issue for my use case.

Version & Environment

vite-plugin-compression2 "^1.1.0"
Node.js v20.13.1, React project

Expection

I'm storing a robots.txt file inside my /public folder. The file gets copied to the /dist folder when I run the build. I expect robots.txt to be bundled on the dist.tar.gz file, even if it's not being compressed.

Actual results (or Errors)

The file is not included in the dist.tar.gz file.

ZSTD?

Feature request 🚀

image

Chromium

Error: ENOENT: no such file or directory

Bug report 🐞

With deleteOriginalAssets: true it seems to delete the assets file early and create 0kb br files.

Generate br files with 0kb:

ChangeLog-3faf1141.js.br : 0kb
ChangeLog-3faf1141.js.gz : 498 bytes
ChangeLog-legacy-d61b07c3.js.br : 0kb
...
Settings-legacy-a607e528.js.br : 0kb

Version & Environment

    "vue": "^3.3.4",
    "vue-i18n": "^9.2.2",
    "vue-meta": "^3.0.0-alpha.2",
    "vue-router": "^4.2.4",
    "vuetify": "^3.3.9",
    "prettier": "^3.0.0",
    "sass": "^1.63.6",
    "vite": "^4.4.4",
    "vite-plugin-compression2": "^0.10.2",
    "@rollup/plugin-terser": "^0.4.3",
    "@vitejs/plugin-legacy": "^4.1.0",
    "@vitejs/plugin-vue": "^4.2.3",
    "vite-plugin-prettier": "^0.0.5",
    "vite-plugin-vuetify": "^1.0.2"
plugins: [
		vue(),
		vuetify({ autoImport: true }),
		legacy({
			targets: ['chrome 61']
		}),
		terser(),
		viteCompression({
			include: [/.js$/, /.css$/]
		}),
		viteCompression({
			algorithm: 'brotliCompress',
			include: [/.js$/, /.css$/],
			exclude: [/\.(br)$/, /\.(gz)$/],
			deleteOriginalAssets: true
		})
	]

Expection

Change to deleteOriginalAssets: false.

Works fine, then just delete all js and css files manually instead of deleting them all automatically.

Actual results (or Errors)

✓ built in 18.82s
node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^

[Error: ENOENT: no such file or directory, open 'D:\web\dist\assets\ChangeLog-legacy-d61b07c3.js'] {
  errno: -4058,
  code: 'ENOENT',
  syscall: 'open',
  path: 'D:\\web\\dist\\assets\\ChangeLog-legacy-d61b07c3.js'
}

Node.js v18.16.0

threshold选项对某些js文件不生效

Bug report 🐞

配置如下

compression({ threshold: 1024 * 80 })

但打包时小于80kb的js文件也被压缩了:
image

具体复现流程:npm init vue@latest创建项目,只选择vue-router功能,引入了本插件并设置threshhold为80*1024,然后build。

Version & Environment

{
  "dependencies": {
    "vue": "^3.3.4",
    "vue-router": "^4.2.2"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^4.2.3",
    "vite": "^4.3.9",
    "vite-plugin-compression2": "^0.10.0"
  }
}

When the 'filename' is set to the original file name '[path][base]' and 'deleteOriginalAssets' is used simultaneously, it will result in the compressed file being deleted as well.

Bug report 🐞

import viteCompression from 'vite-plugin-compression2'
viteCompression({
    algorithm: 'gzip',
    include: /\.(js|svg)$/i,    
    deleteOriginalAssets: true,
    filename: '[path][base]',
  })

Version & Environment

{
  "devDependencies": {
    "vite": "^4.3.9",
    "vite-plugin-compression2": "^0.10.1",
  }
}

Expection

Original file should be deleted,
and the .gz extension should be removed (thus resulting in the same file name as the original).

Actual results (or Errors)

All compressed files and their original files have been deleted.

I suspect it is an issue with the execution order. It is possible that the .gz files were deleted along with the original files based on their original file names after the new names were generated.

Many JS files are not compressed when using build dir !== dist

Bug report 🐞

When vite -> build -> output -> dir is not dist, most of the files don't get compressed.

My app has 25 JS files.

When dir: 'build',, only 1 file is gzipped.

When dir: 'test_directory',, only 1 file is gzipped.

When dir: 'dist',, all 25 files are gzipped.

So it seems the problem is that only dist is supported as a build directory.

Using 0.8.4, my vite.config.ts:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { lingui } from '@lingui/vite-plugin';
import ckeditor5 from '@ckeditor/vite-plugin-ckeditor5';
import compression from 'vite-plugin-compression2';
import eslint from 'vite-plugin-eslint';

// Unix timestamp.
const fileDate = Date.now();

// https://vitejs.dev/config/
export default ({ mode }) => {

  return defineConfig({
    build: {
      // Minimum size of assets; anything smaller than this will be inlined.
      assetsInlineLimit: 4096,
      cssCodeSplit: true,
      rollupOptions: {
        // Hide react-query warnings for server components.
        onwarn(warning, warn) {
          if (warning.code === 'MODULE_LEVEL_DIRECTIVE') {
            return;
          }
          warn(warning);
        },
        output: {
          // This MUST be the same dir as specified in capacitor.config.ts.
          // Otherwise, capacitor will launch to a blank screen.
          dir: 'build',
          experimentalMinChunkSize: 10000,
          manualChunks: {
            // CKEditor5 by itself is over 500 Kb, so split out the engine.
            editorEngine: ['@ckeditor/ckeditor5-engine'],
          },
        },
      },
      sourcemap: false,
    },
    plugins: [
      eslint(),
      react({
        // Needed for lingui.
        babel: {
          plugins: ['macros'],
        },
      }),
      ckeditor5({ theme: require.resolve('@ckeditor/ckeditor5-theme-lark') }),
      lingui(),
      compression({
        algorithm: 'gzip',
        exclude: [/\.(br)$ /, /\.(gz)$/],
        deleteOriginalAssets: false,
      }),
    ],
  });
};

Version & Environment

0.8.4, macOS + Ubuntu

Thanks for creating this awesome plugin!

need some help after compression success

Can someone guide me how to allow gz or br files to be loaded on a website? I have created a frontend project and I want to deploy it using Netlify. But there is a failure, files compressed using br cannot be loaded. What should i do ?

Screenshot 2023-10-30 120122
image

image

[help]配置不生效

nginx里配置了brotli,vite中也配置了,但是实际只有少数几个压缩前1kb以下的js和css文件会使用br,其它都是gzip,不知道是哪里没配置对。

index.xxx.js // 大于1k
index.xxx.js.br // 小于1k

vite.config.ts:

import { compression } from "vite-plugin-compression2";

compression({
    threshold: 1024,
    algorithm: "brotliCompress",
}),

nginx.conf:

    gzip on;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

    brotli on;
    brotli_static on;
    brotli_comp_level 11;
    brotli_buffers 16 8k;
    brotli_min_length 1;
    brotli_types text/plain text/css text/javascript application/javascript  application/json image/jpeg image/gif image/png;

Compression is performed at the stage `configResolved`

I use prerender plugin in my project, it will launch a browser with my compile product at the stage generateBundle, but this plugin completes the compression before that. Cause my html inside gz is the origin template, not the prerendered one, but outside the gz file, there is the prerendered html file.
Can it be solved? Thank you.

使用 `import compression from 'vite-plugin-compression'` 时运行报错 `TypeError: compression is not a function`

Bug report 🐞

https://github.com/ModyQyW/playground

  • yarn install
  • yarn dev

Version & Environment

$ node -v
v18.13.0
$ yarn -v
1.22.19

我已阅读过文档,文档内的建议用法是 import { compression } from 'vite-plugin-compression'

但我倾向于使用默认导入,而且代码内也有默认导出,没有提示类型错误,不太明白为什么不能使用 import compression from 'vite-plugin-compression'

Expection

正常运行

Actual results (or Errors)

image

`deleteOriginalAssets` option removes `manualChunks`

Bug report 🐞

With this build config, the plugin seems to remove chunking strategy when using deleteOriginalAssets option:

plugins: [
      react({
        fastRefresh: process.env.NODE_ENV !== 'test'
      }),
      compression({ deleteOriginalAssets: true })
    ],
build: {
      rollupOptions: {
        output: {
          manualChunks: function manualChunks(id) {
            if (id.includes('node_modules')) {
              if (id.includes('lodash')) {
                return 'lodash'
              }
              if (id.includes('moment')) {
                return 'moment'
              }
              if (id.includes('leaflet')) {
                return 'leaflet'
              }
              if (id.includes('datadog')) {
                return 'datadog'
              }
              return 'vendor'
            }
            if (id.includes('components/icons')) {
              return 'icons'
            }
            if (id.includes('helpers/translations')) {
              return 'translations'
            }
          }
        }
      }
    }

Do you have an idea why?
Thanks

Version & Environment

"@vitejs/plugin-react": "^4.0.2",
"vite": "^4.4.0",
"vite-plugin-compression2": "^0.10.2",

Expectation

Manual chunks should be generated:

image

Actual results (or Errors)

Manual chunks are not generated anymore:

image

不支持static文件压缩

原来从vite-plugin-compress迁移过来的,但是换成2之后static文件压缩没了。

我们项目里static文件可是多了去了,必须压缩的。。。所以。。。。

强烈建议加上static文件的压缩

【功能请求】可以将打包后的 dist 目录打包成 *.tar.gz 压缩包

目前已经支持将单个文件压缩成 gz 和 br 文件,可以添加一个功能,当打包完成后将 dist 压缩成一个 *.tar.gz 文件。这样部署到 Linux 系统时更加友好,大致详细需求如下:

  1. 可以配置压缩包的名字
  2. 最好可以自动在压缩包名字后添加版本号
  3. 可以配置是否保留压缩包内的根目录,以及可以配置这个根目录的名称(这个名称跟压缩包的名字不同,例:压缩包的名字为 example-app-1.0.0.tar.gz,内部根目录名字为 example-app
  4. 也可以支持多种压缩算法,比如支持压缩为 zip。

[vite-plugin-compression] Error running plugin hook generateBundle for vite-plugin-compression, expected a function hook. error during build: Error: Error running plugin hook generateBundle for vite-plugin-compression, expected a function hook. at error (file:///Users/admin/work/xx/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/rollup.js:1858:30)

使用pnpm
版本信息:
"vite": "^3.0.7",
"vite-plugin-compression2": "^0.6.3",

报错:
[vite-plugin-compression] Error running plugin hook generateBundle for vite-plugin-compression, expected a function hook. error during build: Error: Error running plugin hook generateBundle for vite-plugin-compression, expected a function hook. at error (file:///Users/admin/work/xx/node_modules/.pnpm/[email protected]/node_modules/rollup/dist/es/shared/rollup.js:1858:30)

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.