You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Firebase项目构建报错WEBPACK_IMPORTED_MODULE_5__.default.collection is not a function的解决方案咨询

Fixing "collection is not a function" Error in Firebase v9 + React

Yep, you’re totally right about this being a Firebase v9 API shift—they moved to a modular, tree-shakeable system that replaces the old chained method calls like db.collection(). Let’s get your code fixed step by step:

Step 1: Add the right Firestore imports to your component

Instead of relying on methods attached to the db object, you’ll need to import specific standalone functions from firebase/firestore:

import { doc, getDoc } from "firebase/firestore";

Step 2: Rewrite the document reference and fetch logic

In Firebase v9, you create document references with the doc() function, and fetch them using getDoc() (replacing the old .get() method). Here’s your updated component code:

const { id } = useParams();
const [detailData, setDetailData] = useState({});

useEffect(() => {
  // Create a reference to the target movie document
  const docRef = doc(db, "movies", id); // Shorthand: doc(db, collectionName, documentId)
  
  // Fetch the document with v9's getDoc()
  getDoc(docRef)
    .then((docSnapshot) => {
      if (docSnapshot.exists()) { // Note: v9 uses the exists() method instead of the exists property
        setDetailData(docSnapshot.data());
      } else {
        console.log("No such document in Firebase!");
      }
    })
    .catch((error) => {
      console.log("Error getting document:", error);
    });
}, [id]);

Quick check on your Firebase config file

Your config setup is already correct—you’re properly exporting the db instance from getFirestore(app). No changes needed here!

Bonus: Temporary compat mode (if you prefer v8 syntax)

If you want to stick with the old chained calls for a bit, you can use Firebase’s compat libraries. Just update your config file imports to use the /compat suffix:

// In your Firebase config file
import firebase from "firebase/compat/app";
import "firebase/compat/firestore";
import "firebase/compat/auth";
import "firebase/compat/storage";

const app = firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
// ... rest of your exports

That said, the modular approach is recommended long-term because it lets tree-shaking remove unused code, making your bundle smaller.

内容的提问来源于stack exchange,提问作者Archit Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:28:14