VitePress 支持 gzip 和 brotli 压缩与部署
打包压缩
安装 vite-plugin-compression
shellnpm i vite-plugin-compression -D
在.vitepress/config.js 中增加如下配置
jsimport {createWriteStream} from "fs"; import {defineConfig} from "vitepress" import viteCompression from "vite-plugin-compression"; // https://vitepress.dev/reference/site-config export default defineConfig({ vite: { plugins: [ viteCompression({ verbose: true, disable: false, threshold: 10240, algorithm: "gzip", ext: ".gz", }), viteCompression({ verbose: true, disable: false, threshold: 10240, algorithm: "brotliCompress", ext: ".br", }), ], }, ... })
vite-plugin-compression 在 vitepress 只能打包 dist/assets/ 下面的代码,所以不要修改默认的输出地址。
对 html 代码进行.gzip 和.br 压缩
创建 comporess.js 文件
shell# windows: ni ./vitepress/comporess.js touch ./vitepress/comporess.js
安装 fast-glob
shellnpm i fast-glob -D
./vitepress/comporess.js 文件内容如下
javascriptimport {promises as fs} from "fs"; import {gzip, brotliCompress} from "zlib"; import {promisify} from "util"; import fg from "fast-glob"; const gzipAsync = promisify(gzip); const brotliCompressAsync = promisify(brotliCompress); async function compressFiles() { try { // 使用 fast-glob 直接获取所有 HTML 文件的路径 const files = await fg("./dist/**/*.html", {onlyFiles: true}); for (const file of files) { const content = await fs.readFile(file); // Gzip const gzipped = await gzipAsync(content); await fs.writeFile(`${file}.gz`, gzipped); // Brotli const brotlied = await brotliCompressAsync(content); await fs.writeFile(`${file}.br`, brotlied); } console.log("Compression complete."); } catch (error) { console.error("Error during compression:", error); } } compressFiles();
package.json 增加 compress 命令
json"scripts": { "start": "npm run dev", "dev": "vitepress dev --host 0.0.0.0", "build": "vitepress build", "preview": "vitepress preview", "compress": "node ./.vitepress/comporess.js", "postbuild": "npm run compress", "deploy": "docker-compose build && docker-compose down && docker-compose up -d" },
nginx 支持 gzip 文件转发
打包之后需要转发,还需要在 NGINX 配置文件中增加支持
nginx
server {
listen 80;
server_name localhost;
root "D:/phpstudy_pro/WWW";
location / {
index index.php index.html;
autoindex off;
gzip_static on; #开启静态 .gz 文件转发
brotli_static on; #开启静态 .br 文件转发, 需要安装插件、在 HTTPS 下才能开启
}
}
参考文章
https://docs.ffffee.com/vitepress/vitepress-gzip-brotli-config.html