如何修复使用Firebase JS时出现的getDatabase导出错误
解决Firebase JS中
getDatabase导出不存在的语法错误 问题根源很明确:你把Realtime Database相关的API(getDatabase、ref、push)错误地从firebase-app.js导入了——这个文件只负责Firebase核心功能的初始化,数据库操作的方法属于独立的模块文件。
修正步骤
把数据库相关API的导入路径替换为firebase-database.js,修改后的完整代码如下:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js' // 替换为数据库专属模块文件 import { getDatabase, ref, push } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js' const appSettings = { databaseURL : 'https://playground-5d1ab-default-rtdb.firebaseio.com/' } const app = initializeApp(appSettings); const database = getDatabase(app); const shoppingListInDB = ref(database, "shoppingList"); const inputBtn = document.getElementById("input-field"); const cartBtn = document.getElementById("button-id"); const shoppingListEl = document.getElementById("shopping-list"); cartBtn.addEventListener("click", function(){ let inputValue = inputBtn.value; push(shoppingListInDB, inputValue); console.log(inputValue); shoppingListEl.innerHTML += `<li>${inputValue}</li>`; // 可选:点击后清空输入框,提升体验 inputBtn.value = ''; })
额外提示
如果后续使用Firebase的其他服务(比如身份验证、云Firestore),也要对应导入各自的模块文件,比如firebase-auth.js、firebase-firestore.js,不能都从firebase-app.js里调用。
内容的提问来源于stack exchange,提问作者pinkcuracao
相关产品推荐
相关产品推荐

