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

Firebase初始化后点击谷歌登录按钮出现'Uncaught ReferenceError: firebase is not defined'错误求助

解决“Uncaught ReferenceError: firebase is not defined”问题

哈哈,这个坑我刚接触Firebase 9的时候也踩过!问题出在你混用了Firebase的新旧两种API写法:你在firebase.js里用的是Firebase 9+的模块化导入方式,但custom.js里还在沿用旧版本的全局命名空间写法(直接调用firebase.auth),而Firebase 9+已经不再默认暴露全局的firebase对象了,所以浏览器找不到它就报错了。

咱们一步步改就能解决:

第一步:修改firebase.js,导出Auth相关对象

需要先导入Auth模块,初始化后把它和Google登录提供者导出,这样custom.js才能用:

// FIREBASE INITIALIZATION
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.3.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.3.0/firebase-analytics.js";
// 新增导入Auth和Google登录提供者
import { getAuth, GoogleAuthProvider } from "https://www.gstatic.com/firebasejs/9.3.0/firebase-auth.js";

const firebaseConfig = {
  apiKey: "XXXXXXXX",
  authDomain: "fir-chat-application-3e442.firebaseapp.com",
  projectId: "fir-chat-application-3e442",
  storageBucket: "fir-chat-application-3e442.appspot.com",
  messagingSenderId: "264006913204",
  appId: "XXXXXXXX",
  measurementId: "XXXXXXXX"
};

const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
// 初始化Auth并导出
export const auth = getAuth(app);
export const googleProvider = new GoogleAuthProvider();

第二步:调整custom.js为模块并修改登录逻辑

首先要把HTML里的custom.js脚本标签改成模块类型,不然没法导入其他模块:

<script src="js/custom.js" type="module"></script>

然后修改custom.js的代码,导入需要的对象,并用模块化方式实现登录:

// 从firebase.js导入我们导出的auth和googleProvider
import { auth, googleProvider } from './firebase.js';

function signIn(){
  // 用Firebase 9的模块化方法调用登录弹窗
  auth.signInWithPopup(googleProvider)
    .then((result) => {
      // 这里可以写登录成功后的逻辑,比如获取用户信息
      const user = result.user;
      console.log("登录成功啦:", user);
    })
    .catch((error) => {
      // 处理登录失败的情况
      console.error("登录出错了:", error);
    });
}

// 注意:模块里的函数是私有作用域,要挂载到window上,HTML按钮才能调用到它
window.signIn = signIn;

为什么这样改?

  • Firebase 9+ 采用了ES模块化设计,不再提供全局的firebase对象,所有功能都需要通过导入对应的模块来使用。
  • 把custom.js设为模块后,才能导入firebase.js里导出的对象。
  • 模块内部的函数默认不会暴露到全局,所以要把signIn挂到window上,这样HTML里的onclick="signIn()"才能找到这个函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 01:52:32