ReactJS中firebase.initializeApp不是函数问题求助
Hey there, let's work through this Firebase auth issue you're hitting in your React app! It sounds like you fixed one error (the "length is undefined" one) by removing the apps.length check, but now you're stuck with firebase.initializeApp is not a function—and the Node.js solutions you found don't apply. Here are the most likely fixes tailored to React:
1. You're using Firebase v9+ but following a v8 tutorial
Firebase v9 switched to a modular API, which breaks the old "namespace" style imports that many tutorials use. If you installed the latest Firebase version, you have two options:
Option A: Use Firebase's Compat Mode (keep the tutorial's syntax)
Compat mode lets you use the old v8-style code with v9+. Update your Firebase imports like this:
// In your firebase config file (e.g., firebase.js) import firebase from 'firebase/compat/app'; import 'firebase/compat/auth'; // Add other services you need (firestore, storage, etc.) with compat const firebaseConfig = { // Your Firebase project config here }; // Now you can safely add back the apps.length check (it works in compat mode!) if (!firebase.apps.length) { firebase.initializeApp(firebaseConfig); } export const auth = firebase.auth(); export default firebase;
The "length is undefined" error you saw earlier was probably because you were importing the non-compat v9 firebase/app which doesn't expose the apps property in the old way.
Option B: Downgrade to Firebase v8
If you want to stick exactly to the tutorial's code without changing imports, downgrade your Firebase package to a v8 version:
npm install firebase@8.10.0 # or yarn add firebase@8.10.0
After downgrading, your original import (import firebase from 'firebase/app') and initialization code should work as expected, including the apps.length check.
2. Double-check your import and initialization code
Even if you think it's not a spelling issue, quickly verify:
- You're importing from
firebase/compat/app(v9+) orfirebase/app(v8) — not a typo likefirebase/appsor something else. - You're calling
firebase.initializeApp()(capital "A"), notfirebase.initializeapp(). - Your Firebase config object is correctly copied from the Firebase console (no missing keys or typos there).
3. Ensure initialization runs only once
Make sure your Firebase initialization code lives in a separate file (like firebase.js) that you import into components as needed. Don't put the initialization code directly inside a component (like App.js), because that could run multiple times as the component re-renders, causing unexpected errors.
Once you adjust your import style or downgrade the version, you should be able to add back the if (!firebase.apps.length) check to prevent duplicate initialization, and the initializeApp is not a function error should disappear.
内容的提问来源于stack exchange,提问作者devdc

