Svelte集成Firebase时出现firestore()/auth()未解析错误是什么原因?
问题原因
- 核心诱因是Firebase版本与代码语法不匹配:你编写的代码适配的是Firebase 8.x版本的命名空间调用规则,若你安装的是9.x及更高版本的Firebase,官方已将默认API改为模块化导入方案,旧版
firebase.auth()、firebase.firestore()这类挂载在全局firebase对象下的方法不再默认支持,因此会抛出方法未找到的报错。 - 小概率为编辑器索引异常:如果已经确认Firebase版本与语法匹配,可能是IDE未正确加载依赖的类型定义文件,重启编辑器或刷新项目依赖索引即可恢复。
解决方案
方案1:降级到Firebase 8.x版本(无需修改现有代码)
直接安装对应版本的Firebase依赖即可,运行命令:
npm install firebase@8.10.0 # 若使用yarn则运行 yarn add firebase@8.10.0
安装完成后重启项目即可正常运行你当前的代码。
方案2:适配9.x及以上版本的Firebase语法(推荐,打包体积更小、性能更优)
兼容模式(几乎不用修改现有业务代码)
调整firebase.js的导入路径为compat兼容包即可:
import firebase from 'firebase/compat/app'; import 'firebase/compat/auth'; import 'firebase/compat/firestore'; const firebaseConfig = { // 你的配置内容 }; firebase.initializeApp(firebaseConfig); export const auth = firebase.auth(); export const googleProvider = new firebase.auth.GoogleAuthProvider(); export const db = firebase.firestore();
纯模块化写法(官方推荐写法)
完全适配新版API,可获得最优的tree shaking效果,减少打包体积:
import { initializeApp } from 'firebase/app'; import { getAuth, GoogleAuthProvider } from 'firebase/auth'; import { getFirestore } from 'firebase/firestore'; const firebaseConfig = { // 你的配置内容 }; const app = initializeApp(firebaseConfig); export const auth = getAuth(app); export const googleProvider = new GoogleAuthProvider(); export const db = getFirestore(app);
内容的提问来源于stack exchange,提问作者user15258189
相关产品推荐
相关产品推荐

