无法读取未定义的属性(读取 'firestore')

Cannot read properties of undefined (reading 'firestore')

我试图将我的 firebase 项目导入 expo,但出现错误“firebase.js:15 Uncaught TypeError: 无法读取未定义的属性(读取 'firestore')”。我有这样的 firestore 应用程序:

import firebase, { initializeApp } from "firebase/app";
import "firebase/firestore";

const firebaseConfig = {
  apiKey: "xxx",
  authDomain: "xxx",
  projectId: "xxx",
  storageBucket: "xxx",
  messagingSenderId: "xxx",
  appId: "xxx",
};

initializeApp(firebaseConfig);

const db = firebase.firestore();

export { db };

还要从 firebase 导入 initializeapp,否则错误是“firebase.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'initializeApp')”

我使用的 firebase 版本是 "firebase": "^9.8.1",

对我来说,当我使用 Expo 时,我发现我必须使用路径:

firebase/compat/app

firebase/compat/firestore

相反,所以像这样;

import firebase from "firebase/compat/app";
import "firebase/compat/firestore";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
};

const app = firebase.initializeApp(firebaseConfig);

export const db = app.firestore();

此外,我建议使用略有不同的声明方式,如上所示,将应用程序声明为常量,因为它更好,以防您需要添加更多导出,例如:

const app = firebase.initializeApp(firebaseConfig);

export const auth = app.auth();
export const db = app.firestore();
export const storage = app.storage();

试一试,看看是否有效