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

Firebase v9使用时报错"Firebase Not Defined"的问题咨询

问题原因分析

你认为「加载了firebase-app.js就会定义全局firebase变量」的想法是错误的。Firebase 9的模块化版本(也就是你当前导入的CDN版本)完全移除了全局firebase变量暴露的逻辑,这和8.x及更早的版本完全不同。你跟着2019年教程写的firebase.xxx调用写法在v9模块化版本里已经废弃,这就是你报错的直接原因。

解决方法

有两种方案可选:

方案1:使用v9原生模块化语法(推荐)

不需要全局firebase对象,所有功能都需要单独导入对应模块的方法使用:

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
// 以Firestore数据库为例,需要用到什么服务就导入对应模块的方法
import { getFirestore, collection, addDoc } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js";

// 替换为你自己的Firebase项目配置
const firebaseConfig = {
  apiKey: "你的项目参数",
  authDomain: "你的项目参数",
  projectId: "你的项目参数",
  storageBucket: "你的项目参数",
  messagingSenderId: "你的项目参数",
  appId: "你的项目参数"
};

// 初始化App实例
const app = initializeApp(firebaseConfig);
// 初始化数据库实例
const db = getFirestore(app);

// 数据提交操作直接调用导入的方法即可,示例:
async function submitData() {
  try {
    const res = await addDoc(collection(db, "你的集合名称"), {
      字段1: "值1",
      字段2: "值2"
    });
    console.log("提交成功,文档ID:", res.id);
  } catch (err) {
    console.error("提交失败:", err);
  }
}

方案2:使用v9兼容模式,适配旧教程写法

如果你不想修改旧教程里的firebase.xxx调用逻辑,可以导入兼容版CDN资源,兼容版会暴露全局firebase变量,和旧版本用法完全一致:

// 导入兼容版核心库
import firebase from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app-compat.js";
// 用到的其他服务也要导入对应的兼容版
import "https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore-compat.js";

const firebaseConfig = {
  // 你的项目配置
};

firebase.initializeApp(firebaseConfig);
// 后续就可以直接用旧写法调用,示例:
const db = firebase.firestore();
db.collection("集合名称").add({字段: "值"});
注意事项
  • 所有导入的Firebase相关CDN资源版本号必须完全一致,避免出现依赖冲突
  • 如果你选择原生模块化写法,代码中不要出现任何firebase.xxx格式的调用,所有功能都通过导入的独立方法实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:09:02