首次配置Firebase报错firestore is not a function该如何解决?
问题原因
你的报错是Firebase v9+版本中混用模块化API与compat兼容API、导入路径不匹配导致的:
- 你同时导入了新版模块化核心包
firebase/app和旧版兼容包firebase/compat/app,两种API逻辑冲突 - 要使用compat模式下的Firestore能力,需要导入对应兼容包路径
firebase/compat/firestore,你导入的firebase/firestore是模块化版本的导出,不会挂载到firebase实例上,因此调用firebase.firestore()时找不到对应方法
解决方案
方案1:沿用compat兼容写法
统一使用compat包导入即可,修改后代码如下:
// Import the functions you need from the SDKs you need import firebase from 'firebase/compat/app'; import 'firebase/compat/firestore'; // Your web app's Firebase configuration const firebaseConfig = { apiKey: "x", authDomain: "x", projectId: "x", storageBucket: "x", messagingSenderId: "x", appId: "x" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); const db = firebase.firestore(); export { db };
方案2:使用官方推荐的新版模块化API(更推荐)
不需要引入compat兼容包,直接用v9+原生模块化写法,性能更好、打包体积更小,修改后代码如下:
// Import the functions you need from the SDKs you need import { initializeApp } from "firebase/app"; import { getFirestore } from "firebase/firestore"; // Your web app's Firebase configuration const firebaseConfig = { apiKey: "x", authDomain: "x", projectId: "x", storageBucket: "x", messagingSenderId: "x", appId: "x" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const db = getFirestore(app); export { db };
内容的提问来源于stack exchange,提问作者BLACKDICK
相关产品推荐
相关产品推荐

