在我的 ionic React 项目中,我尝试使用官方谷歌文档来实现 firebase 的 firestore。但是,我的 IDE 中出现错误
const db = firebase.firestore();
这是我收到的错误,其中 PROJECT_FOLDER 是我的项目的主管。
类型 'typeof import("PROJECT_FOLDER/node_modules/firebase/app/dist/app/index")'.ts(2339)' 上不存在属性 'firestore'
奇怪的是,我的 IDE 可以识别一些已安装的软件包功能,例如
firebase.initializeApp()
,但不能识别 firebase.firestore()
。我的package.json下的firebase和firestore版本分别是10.8.0和4.4.2。任何反馈都会很有用,因为我对打字稿还比较陌生。
当前实施
import firebase from "firebase/app";
import "firebase/firestore";
// TODO: Replace the following with your app's Firebase project configuration
// See: https://support.google.com/firebase/answer/7015592
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID',
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize Cloud Firestore and get a reference to the service
const db = firebase.firestore();
db.collection("users").add({
first: "Ada",
last: "Lovelace",
born: 1815
})
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
我发现我的实施存在问题。我使用 Web 模块化 API 格式来导入和设置 firebase 和 firestore,并使用 Web 命名空间 API 格式添加到数据库。不知道为什么 VS Code 没有识别出使用了不正确的导入方法,但无论如何。
我的代码应该是什么
import { initializeApp } from "firebase/app";
import { getFirestore, collection, addDoc } from "firebase/firestore";
// TODO: Replace the following with your app's Firebase project configuration
// See: https://support.google.com/firebase/answer/7015592
const firebaseConfig = {
apiKey: 'YOUR_API_KEY',
authDomain: 'YOUR_AUTH_DOMAIN',
projectId: 'YOUR_PROJECT_ID',
storageBucket: 'YOUR_STORAGE_BUCKET',
messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
appId: 'YOUR_APP_ID',
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);
try {
const docRef = await addDoc(collection(db, "users"), {
first: "Ada",
last: "Lovelace",
born: 1815
});
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}