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

如何解决Firebase集成中Uncaught ReferenceError: firebase is not defined错误?

解决Uncaught ReferenceError: firebase is not defined问题

问题原因

你使用的是Firebase v9的模块化导入模式(通过import加载核心库),这种模式不会在全局作用域生成firebase全局对象;但你的Firebase UI v6代码仍依赖旧版命名空间风格的firebase变量,因此触发了引用错误。

修复方案

方案1:改用Firebase兼容层导入(最省心)

直接切换到Firebase v9的兼容层(compat)导入,它会自动在全局创建firebase对象,完美适配你当前的Firebase UI代码:

<script type="module">
  // 导入兼容层核心库
  import firebase from "https://www.gstatic.com/firebasejs/9.15.0/firebase.js";
  // 按需导入兼容层的子模块
  import "https://www.gstatic.com/firebasejs/9.15.0/firebase-analytics-compat.js";
  import "https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore-compat.js";
  import "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth-compat.js";

  const firebaseConfig = {
    // 你的Firebase配置信息
  };

  // 用兼容方式初始化应用
  const app = firebase.initializeApp(firebaseConfig);
  const analytics = firebase.analytics(app);
  const db = firebase.firestore(app);

  async function getCities(db) {
    const citiesCol = db.collection('cities');
    const citySnapshot = await citiesCol.get();
    return citySnapshot.docs.map(doc => doc.data());
  }
</script>

方案2:手动在全局暴露所需对象(保留纯模块化模式)

如果不想修改初始化模式,可在模块化脚本中将Firebase UI需要的auth相关对象挂载到window上:

<script type="module">
  import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
  import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-analytics.js";
  import { getFirestore, collection, getDocs } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore.js";
  // 导入auth核心及兼容层的EmailAuthProvider
  import { getAuth } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js";
  import { EmailAuthProvider } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth-compat.js";

  const firebaseConfig = {
    // 你的Firebase配置信息
  };

  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);
  const db = getFirestore(app);
  const auth = getAuth(app);

  // 挂载Firebase UI需要的对象到全局
  window.firebase = {
    auth: () => auth,
    auth: {
      EmailAuthProvider: EmailAuthProvider
    }
  };

  async function getCities(db) {
    const citiesCol = collection(db, 'cities');
    const citySnapshot = await getDocs(citiesCol);
    return citySnapshot.docs.map(doc => doc.data());
  }
</script>

额外提醒

  • signInSuccessUrl、tosUrl要写成完整URL,比如http://localhost:5500,否则会被解析为当前页面的相对路径,导致跳转异常。
  • 如果后续想彻底升级到模块化开发模式,可将Firebase UI升级到v7及以上版本,使用其对应的模块化导入方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:50:26