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

部署Vite + React项目至Firebase时遭遇MIME类型错误求助

Vite + React部署Firebase后页面空白,MIME类型错误排查

部署Vite+React项目到Firebase后,部署流程显示成功,但访问页面无内容,控制台报错:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

试过修改firebase.json的路径配置、调整vite.config.js的base值,都没解决问题。以下是相关配置文件:

dist/assets下的index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <link rel="icon" type="image/svg+xml" href="/dynamic-dictionary/vite.svg" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Dynamic Dictionary</title>
  <script type="module" crossorigin src="/dynamic-dictionary/assets/index-a6323fd3.js"></script>
  <link rel="stylesheet" href="/dynamic-dictionary/assets/index-b1761384.css">
</head>

<body>
  <div id="root"></div>

</body>

</html>

firebase.json

{
  "hosting": {
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }],
    "frameworksBackend": {
      "region": "us-central1"
    }
  }
}

vite.config.js

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

export default defineConfig(({ command }) => {
  const config = {
    plugins: [svgr(), react()],
    base: '/',
  }

  if (command !== 'serve') {
    config.base = '/dynamic-dictionary/'
  }

  return config
})

可能的问题根源及解决办法

1. 重写规则拦截了静态资源请求

vite配置中生产环境base设为/dynamic-dictionary/,所有静态资源路径都以这个前缀开头,但firebase的重写规则"source": "**"会把所有请求(包括静态资源)都转发到/index.html。浏览器请求JS文件时,得到的是index.html内容,自然触发MIME类型错误。

修复: 修改firebase.json的rewrites规则,排除静态资源路径:

"rewrites": [
  {
    "source": "!/dynamic-dictionary/**",
    "destination": "/index.html"
  }
]

这样只有非静态资源的路由请求才会被转发到index.html,静态资源能正常加载。

2. index.html存放路径错误

正常Vite打包后,index.html应该在dist根目录下,但你的index.html在dist/assets里。Firebase默认会找dist/index.html作为入口,找不到时会触发重写,导致资源请求路径混乱。

修复: 把index.html移到dist根目录,确保Firebase能直接找到入口文件,同时检查index.html内的资源路径是否正确(当前路径是/dynamic-dictionary/assets/...,移到根目录后路径无需修改)。

3. Firebase public目录配置与实际结构不匹配

firebase.json中public设为dist,但如果dist根目录没有index.html,Firebase无法正确定位入口,会导致后续重写逻辑出错。

修复: 确保dist根目录存在index.html,或者如果非要放在assets里,把public改为dist/assets(不推荐,会导致静态资源路径冲突)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 10:35:03