- You can call me
Kanno
- I've been busy recently
- Learning
zig
nonzzz / vite-plugin-compression Goto Github PK
View Code? Open in Web Editor NEWvite plugin. compress your bundle file.
License: MIT License
vite plugin. compress your bundle file.
License: MIT License
最新的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吧 :)
Added default value for include option.
It is better to compress only text files, not images, video and audio.
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样式不生效
compression({ deleteOriginalAssets: true, include: [/\.(js)$/, /\.(css)$/, /\.(mjs)$/, /\.(json)$/] }),
当我使用vite-plugin-compression
时,样式是正常的 我不确定具体是什么导致这个问题的产生
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"
}
}
只有第一层文件夹的 .gz
和 .br
文件输出到控制台了,但实际上所有文件都正确输出压缩文件到 dist/
目录下了。
# 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.
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?
export default defineConfig({
build: {
rollupOptions: {
output: [{ dir: 'es' }, { dir: 'cjs' }]
}
},
})
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'
}
vite: "4.1.4"
vite-plugin-compression2: "0.9.2"
我想要压缩 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",
}),
],
},
}),
});
构建过程报错
⠹ 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 是可以正常构建并压缩的。
构建后体积从原本的4M,变成了6M,体积变的更大
Hi! I was just trying to use this component, but I found a small issue for my use case.
vite-plugin-compression2 "^1.1.0"
Node.js v20.13.1, React project
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.
The file is not included in the dist.tar.gz
file.
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
"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
})
]
Change to deleteOriginalAssets: false
.
Works fine, then just delete all js and css files manually instead of deleting them all automatically.
✓ 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
配置如下
compression({ threshold: 1024 * 80 })
具体复现流程:npm init vue@latest
创建项目,只选择vue-router功能,引入了本插件并设置threshhold为80*1024,然后build。
{
"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"
}
}
Does it compress images
Add additional text-based file formats to the default regex.
Change default regex to:
/\.(html|xml|css|json|js|mjs|svg|yaml|yml|toml)$/
I had some issues typing a object that holds the options for this plugin:
const obj = {}; // which type?
const plugins = [compression(obj)];
I think the correct type for obj
would be ViteWithoutCompressionPluginConfigFunction
but this module currently does not export it.
Can it be exported? Possibly under a more memorable name?
是否有破坏性更新,在最新版本中生产环境无法工作
import viteCompression from 'vite-plugin-compression2'
viteCompression({
algorithm: 'gzip',
include: /\.(js|svg)$/i,
deleteOriginalAssets: true,
filename: '[path][base]',
})
{
"devDependencies": {
"vite": "^4.3.9",
"vite-plugin-compression2": "^0.10.1",
}
}
Original file should be deleted,
and the .gz extension should be removed (thus resulting in the same file name as the original).
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.
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,
}),
],
});
};
0.8.4, macOS + Ubuntu
Thanks for creating this awesome plugin!
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;
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.
https://github.com/ModyQyW/playground
$ node -v
v18.13.0
$ yarn -v
1.22.19
我已阅读过文档,文档内的建议用法是 import { compression } from 'vite-plugin-compression'
。
但我倾向于使用默认导入,而且代码内也有默认导出,没有提示类型错误,不太明白为什么不能使用 import compression from 'vite-plugin-compression'
。
正常运行
exclude设置没有生效
The exclude setting has not taken effect
We can simplify brotli
example after default value for include
option was added.
#49
When I used this tool to gzip the element-plus package, the compressed file I got was wrong and could not be used.
vue3 + vite project
I hope the compressed product can be used normally.
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
"@vitejs/plugin-react": "^4.0.2",
"vite": "^4.4.0",
"vite-plugin-compression2": "^0.10.2",
Manual chunks should be generated:
Manual chunks are not generated anymore:
原来从vite-plugin-compress迁移过来的,但是换成2之后static文件压缩没了。
我们项目里static文件可是多了去了,必须压缩的。。。所以。。。。
强烈建议加上static文件的压缩
目前已经支持将单个文件压缩成 gz 和 br 文件,可以添加一个功能,当打包完成后将 dist 压缩成一个 *.tar.gz 文件。这样部署到 Linux 系统时更加友好,大致详细需求如下:
example-app-1.0.0.tar.gz
,内部根目录名字为 example-app
)使用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)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.