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

部署到Firebase Hosting的React应用报Unexpected token '<'语法错误

问题排查与解决步骤

1 清理残留的旧Service Worker

核心问题是你之前部署过带Service Worker的版本,就算现在注释了注册逻辑,已访问过用户浏览器中安装的旧Service Worker仍然会继续生效,它会优先返回缓存的旧index.html,而旧index.html中引用的带hash的JS/CSS资源已经被新部署的版本替换,因此会报资源加载错误,这也是为什么清空缓存强制刷新能正常访问,普通刷新就报错的原因。
解决方法:

  • 在项目入口JS(一般为src/index.js)最顶部添加Service Worker全局卸载逻辑:
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.getRegistrations().then(function(registrations) {
    for(let registration of registrations) {
      registration.unregister()
    }
  })
}
  • 同步添加浏览器缓存清理逻辑,彻底删除旧缓存内容:
if ('caches' in window) {
  caches.keys().then(function(names) {
    for (let name of names) caches.delete(name);
  })
}

2 调整firebase.json缓存规则

你当前仅给serviceWorker.js配置了不缓存,但是index.html也禁止缓存才能保证每次拉取的都是最新版本,带hash的静态资源可以开启长缓存优化加载速度,修改firebase.json的headers字段如下:

{
  "hosting": {
    "public": "build",
    "site": "react-pukinn",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ],
    "headers": [
      {
        "source": "**/*.@(html|json)",
        "headers": [{"key": "Cache-Control", "value": "no-cache, no-store, must-revalidate"}]
      },
      {
        "source": "**/*.@(js|css|png|jpg|svg|ico)",
        "headers": [{"key": "Cache-Control", "value": "max-age=31536000, immutable"}]
      }
    ]
  }
}

3 确认冗余资源引用清理

如果不需要PWA相关功能,确认public/index.html中已经删除所有引用manifest.json、serviceWorker.js的标签,避免后续构建生成冗余内容。

4 重新部署验证

修改完成后先删除本地旧的build文件夹,重新执行npm run build构建最新版本,再执行firebase deploy --force强制部署到Firebase。部署完成后清空浏览器全部缓存再访问,多次普通刷新验证即可。

内容的提问来源于stack exchange,提问作者Lukas Luke Stateczny

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 02:00:03