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

Flutter Web接入Firebase报Cannot use import statement outside a module错误

错误核心原因

你当前的错误完全来自index.html的配置冲突:

  • 普通<script>标签默认不支持ES模块import语法,必须添加type="module"属性才可以使用,这是你报错的直接诱因
  • 配置逻辑混用了两种Firebase接入方案:同时引入了Firebase 8版本的全局CDN,又写了仅Firebase 9+版本支持的compat导入语句,版本完全不匹配
  • 你修改的是build/web目录下的index.html,该目录是编译产物目录,每次执行flutter build web都会被覆盖,修改完全不生效

修复步骤

1. 修改项目配置文件

找到项目根目录下web文件夹内的index.html,替换原有Firebase相关的全部script代码为以下内容:

<!-- 引入和你本地Firebase版本匹配的compat版本CDN -->
<script src="https://www.gstatic.com/firebasejs/9.21.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.21.0/firebase-auth-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.21.0/firebase-firestore-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.21.0/firebase-storage-compat.js"></script>
<script>
const firebaseConfig = {
   apiKey: "", // 替换为你自己的项目配置
   authDomain: "",
   projectId: "",
   storageBucket: "",
   messagingSenderId: "",
   appId: ""
};
// 直接使用全局挂载的firebase对象初始化,无需import
firebase.initializeApp(firebaseConfig);
</script>

2. 其他文件无需改动

  • 你现有的main.dart、firebase.json、pubspec.yaml配置均符合版本要求,不需要修改
  • firebase目录下仅存在缓存文件属于正常情况,只要你已经完成过firebase login、firebase init hosting的项目绑定操作即可正常使用

3. 重新编译验证

执行以下命令清理缓存重新编译:

flutter clean
flutter pub get

之后本地调试或打包部署都不会再出现该报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 06:27:02