Firebase Hosting自定义域名更新延迟及MIME类型错误问题求助
- 基于最新版Vite+Vue Router的Vue项目部署到Firebase Hosting后出现以下问题:
- Firebase自带域名(如
mycompany.web.app)可即时生效,但自定义域名(如mycompany.com)的变更需数天才能体现 - 访问自定义域名时页面空白,浏览器控制台报错:
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.
Firefox下报错:
Loading module from “https://staging.company.app/assets/index.3794b176.js” was blocked because of a disallowed MIME type (“text/html”).
Loading failed for the module with source “https://staging.company.app/assets/index.3794b176.js” - 修改
index.html标题并重部署后,自定义域名仍显示旧标题 - 部署到Netlify可正常运行,当前
firebase.json配置如下:
- Firebase自带域名(如
{ "target": "qa", "public": "dist", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ { "source": "**", "destination": "/index.html" } ] }
- 曾尝试添加缓存策略但无效
1. 修正重写规则与缓存配置冲突
当前重写规则"source": "**"会把所有请求(包括静态资源)都指向index.html,导致JS/CSS文件返回text/html类型触发报错。需调整规则,区分静态资源和路由请求:
修改firebase.json为以下配置:
{ "target": "qa", "public": "dist", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ // 优先匹配静态资源,直接返回对应文件 { "source": "/assets/**", "destination": "/assets/**" }, // 路由请求才指向index.html(SPA路由 fallback) { "source": "**", "destination": "/index.html" } ], "headers": [ // 静态资源设置长期缓存+正确MIME类型 { "source": "/assets/**", "headers": [ { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }, { "key": "Content-Type", "value": "application/javascript" } ] }, // index.html设置强制刷新,避免缓存旧内容 { "source": "/index.html", "headers": [ { "key": "Cache-Control", "value": "public, max-age=0, must-revalidate" } ] } ] }
2. 强制刷新Firebase CDN缓存
自定义域名依赖全球CDN,旧缓存未失效会导致变更不生效:
- 登录Firebase控制台,进入对应项目的Hosting页面
- 找到自定义域名,点击「更多选项」>「刷新缓存」
- 输入
/**作为刷新路径,提交请求等待CDN节点更新
3. 验证Vite构建配置
确保Vite的静态资源路径配置正确,在vite.config.js中确认base参数:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import { fileURLToPath, URL } from 'node:url' export default defineConfig({ plugins: [vue()], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } }, base: '/' // 根目录部署时保持此配置,子目录需对应修改 })
4. 清除本地浏览器缓存
访问自定义域名时,按Ctrl+Shift+R(Windows/Linux)或Cmd+Shift+R(Mac)强制刷新,清除本地缓存的旧资源。
内容的提问来源于stack exchange,提问作者Yunus Einsteinium

