You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ViteJS React项目使用vite-plugin-compression压缩后.br文件无法加载求助

Vite+React brotli压缩文件无法加载的解决办法

问题根源

手动修改index.html引用.br文件报错,是因为服务器没返回正确的响应头——浏览器收到.br文件,但不知道这是brotli压缩格式,会把它当成普通文本解析,自然出现语法错误。另外vite-plugin-compression本身不会自动替换index.html里的资源引用,正确的做法是让服务器根据浏览器请求头自动返回压缩文件。

解决步骤

1. 确认插件配置正确

先确保vite.config.js里的vite-plugin-compression配置没问题:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import viteCompression from 'vite-plugin-compression';

export default defineConfig({
  plugins: [
    react(),
    viteCompression({
      algorithm: 'brotliCompress',
      ext: '.br',
      threshold: 10240, // 只压缩大于10KB的文件,避免小文件压缩反而变大
      verbose: true,
      deleteOriginFile: false // 保留原文件,方便回退
    })
  ]
});

执行npm run build后,assets目录下既有原文件又有对应的.br文件就说明配置生效了。

2. 本地预览配置

用vite preview预览时,需要给服务器加响应头,让它识别.br文件。修改vite.config.js的preview配置:

export default defineConfig({
  // ...其他配置
  preview: {
    async middleware(req, res, next) {
      // 给.br文件添加压缩标识和正确的MIME类型
      if (req.url.endsWith('.br')) {
        res.setHeader('Content-Encoding', 'br');
        if (req.url.endsWith('.js.br')) {
          res.setHeader('Content-Type', 'application/javascript');
        } else if (req.url.endsWith('.css.br')) {
          res.setHeader('Content-Type', 'text/css');
        }
      }
      next();
    }
  }
});

再执行vite preview就能正常加载了。

3. 生产环境部署(重点)

生产环境需要服务器配合,根据浏览器的Accept-Encoding请求头自动返回.br文件,以下是主流服务器的配置:

Nginx配置

修改站点配置文件(比如/etc/nginx/sites-available/your-site.conf):

server {
  root /path/to/your/dist; # 你的dist目录路径
  index index.html;

  # 启用brotli静态文件支持
  brotli_static on;
  # 指定哪些文件类型启用brotli
  brotli_types text/plain text/css application/javascript application/json image/svg+xml;

  location / {
    try_files $uri $uri/ /index.html;
  }

  # 优先返回.br文件
  location ~* \.(js|css)$ {
    try_files $uri.br $uri =404;
  }
}

注意:Nginx需要提前安装brotli模块,Ubuntu用户可以安装nginx-extras包,编译安装时要加--with-http_brotli_module参数。

Apache配置

在项目根目录的.htaccess文件(没有就新建)里添加:

RewriteEngine On
# 检查浏览器是否支持brotli
RewriteCond %{HTTP:Accept-Encoding} br
# 检查对应.br文件是否存在
RewriteCond %{REQUEST_FILENAME}.br -f
# 重写请求到.br文件
RewriteRule ^(.*)$ $1.br [L]

# 设置正确的响应头和MIME类型
Header set Content-Encoding "br"
AddType application/javascript .js.br
AddType text/css .css.br

确保Apache启用了mod_rewrite和mod_headers模块。

关键提醒

不要手动修改index.html里的资源引用!服务器会自动处理:当浏览器发送Accept-Encoding: br请求头时,服务器返回.br文件并带上Content-Encoding: br响应头,浏览器会自动解码加载,完全不需要在index.html里写.br后缀。

内容的提问来源于stack exchange,提问作者SpookySkeleton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 21:32:33