【问题标题】:Firebase Modular SDK V9.0.0+ TypeError: Cannot read property 'apps' of undefined firebaseFirebase Modular SDK V9.0.0+ TypeError:无法读取未定义 Firebase 的属性“应用程序”
【发布时间】:2021-10-30 03:21:11
【问题描述】:

我在尝试运行我的 next.js 应用程序时遇到此错误。我尝试了很多方法,但我无法解决这个问题。我正在使用 Firebase 9.0.1

Server Error
TypeError: Cannot read property 'apps' of undefined

This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
.next\server\pages\_app.js (14:13) @ Object../firebase.js

  12 | };
  13 |
> 14 | const app = !firebase.apps.length
     |             ^
  15 |   ? firebase.initializeApp(firebaseConfig)
  16 |   : firebase.app();

这是我的 firebase.js

import firebase from "firebase/app";

// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};

const app = !firebase.apps.length
  ? firebase.initializeApp(firebaseConfig)
  : firebase.app();

const db = app.firestore();
const auth = app.auth();
const provider = new firebase.auth.GoogleAuthProvider();

export { db, auth, provider };

【问题讨论】:

  • 您使用的是哪个版本的 Firebase?你也可以分享完整的代码吗?我看不到 Firebase 的导入位置。如果您使用的是 v9,请使用 getApps().length
  • 我使用的是 firebase 9.0.1
  • 你能用导入更新你的代码吗?我想确认您是否使用了兼容库。
  • 从“firebase/app”导入firebase;这是我的进口

标签: javascript firebase next.js


【解决方案1】:

由于您使用的是新的模块化 SDK v9.0.1,它不使用 firebase. 命名空间,因此您应该使用 getApps() 而不是 firebase.apps

import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"

const firebaseConfig = {...}

if (!getApps().length) {
  //....
}

const app = initializeApp(firebaseConfig)

const db = getFirestore(app)
const auth = getAuth(app)

export {db, auth}

不过,您无需检查 Firebase 是否已在此新 SDK 中初始化。您可以在documentation 中了解有关新语法的更多信息。

同时检查:Getting started with Firebase for web

【讨论】:

    【解决方案2】:

    if(!firebase) 由于新的更新而出错。现在代码是这样的

    import { initializeApp } from "firebase/app";
    import { getFirestore, collection, addDoc, getDocs } from "firebase/firestore";
    
    const firebaseConfig = {
    ...
    };
    
    const app = initializeApp(firebaseConfig);
    const db = getFirestore();
    
    export { addDoc, db, collection };
    

    我建议您重新阅读 firebase 文档,它们非常更新,并且许多视频教程代码无法正常工作。 链接:https://firebase.google.com/docs/web/setup https://firebase.google.com/docs/build

    【讨论】:

    • 注意:这些代码可以在旧项目中完美运行,因为它们是使用以前版本的 firebase 制作的。 firebase 只会在使用新版本的 firebase 制作的新项目中出错。
    猜你喜欢
    • 2022-09-27
    • 1970-01-01
    • 2018-01-22
    • 2018-09-19
    • 1970-01-01
    • 2019-09-28
    • 2019-04-05
    • 2021-12-05
    • 2021-11-25
    相关资源
    最近更新 更多