Flutter应用部署Firebase Hosting添加Rewrite后显示空白页
问题分析
你遇到的核心问题是:添加Rewrite规则后,Firebase Hosting把Flutter应用的静态资源请求(比如main.dart.js、assets下的资源)也重定向到了index.html,导致浏览器拿到HTML内容却尝试当成JS/JSON解析,触发了SyntaxError: Unexpected token '<'错误。本地模拟器正常是因为本地资源加载逻辑和线上的规则匹配优先级存在差异。
解决方案
1. 修正firebase.json的Rewrite规则,优先排除静态资源
修改你的firebase.json,确保静态资源请求不会被重写,只对自定义路由(比如/download)和其他Flutter路由进行重写。示例配置如下:
{ "hosting": { "public": "build/web", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ // 先排除所有静态资源,让这些请求直接返回对应文件 { "source": "!/assets/**", "destination": "$1" }, { "source": "!/*.js", "destination": "$1" }, { "source": "!/*.css", "destination": "$1" }, { "source": "!/*.html", "destination": "$1" }, // 自定义路由重写 { "source": "/download", "destination": "/index.html" }, // 所有其他路由交给Flutter处理 { "source": "**", "destination": "/index.html" } ] } }
2. 恢复index.html的base href为根路径
把index.html中的<base href>改回:
<base href="/">
Firebase Hosting默认部署在域名根目录,不需要用相对路径或环境变量,否则可能导致静态资源路径解析错误。
3. 重新构建并部署
执行以下命令重新构建Flutter应用并部署:
flutter build web --release firebase deploy --only hosting
验证方法
部署前先用本地模拟器测试:
firebase serve --only hosting
打开浏览器访问http://localhost:5000/download,检查控制台是否有资源加载错误,确认静态资源(比如main.dart.js)能正常加载、页面能正常显示后,再部署到线上。
内容的提问来源于stack exchange,提问作者Ferdi
相关产品推荐
相关产品推荐

