Firebase实时数据库报错:Uncaught TypeError: database.ref is not a function 求助
Hey there! No worries at all—we all start somewhere, and your question is totally clear. Let's break down why you're hitting that error and how to fix it.
What's Causing the Error?
You're using Firebase's v9 Modular SDK (the version with import statements and tree-shakable code), but you're trying to use the old v8-style syntax (database.ref()) which doesn't work here. In v9, Firebase moved away from the "namespace" pattern (like firebase.database().ref()) to a function-based approach where you import individual functions for each operation.
Step-by-Step Fix
Add the required imports
You need to import two more functions from the Firebase Realtime Database module:ref(to create a reference to your database path) andupdate(to update the data at that path).Update your database operation code
Replace the olddatabase.ref('/').update(...)call with the v9 modular syntax.
Modified game.js Code
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js"; // Add the two new imports here import { getDatabase, ref, update } from 'https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js'; // Your web app's Firebase configuration const firebaseConfig = { apiKey: "apiKey information", authDomain: "authDomain information", databaseURL: "databaseURL information", projectId: "projectId information", storageBucket: "storageBucket information", messagingSenderId: "messagingSenderId information", appId: "appId information", measurementId: "measurementId information" }; const app = initializeApp(firebaseConfig); const database = getDatabase(app); var player_num = 0; // Display Start Button and increment player count let button = document.createElement('button'); button.innerHTML = "Start"; button.onclick = function () { player_num++; // Update this part to use the v9 functions const dbRef = ref(database, '/'); update(dbRef, { playerCount: player_num }); button.style.display = "none"; }; document.body.appendChild(button);
Bonus Cleanup
In your index.html, you're importing firebase-firestore.js but you're not using Firestore (you're using Realtime Database). You can remove that script tag to reduce unnecessary loading:
<!-- Remove this line since you don't use Firestore --> <script defer type="module" src="https://www.gstatic.com/firebasejs/9.1.3/firebase-firestore.js"></script>
A Quick Note
Going forward, when you look up Firebase documentation, make sure you're viewing the "Modular SDK" version (not the "Namespaced" version) since that's what you're using. The modular approach helps keep your bundle size smaller by only including the functions you actually use.
内容的提问来源于stack exchange,提问作者user16620897

