从node_modules导入firebase不工作

goucqfw6  于 2023-03-19  发布在  其他
关注(0)|答案(2)|浏览(144)

我在htdocs目录下创建了一个名为firestore的文件夹,并使用cmd在firestore目录下安装npm firebase。它会生成package.json、package-lock.json和node_modules。我想链接到firebase,但它不起作用。出于隐私原因,我拿走了firebaseconfig密钥。是的,我确实在firebase中创建了一个firestore数据库项目。当我使用import { initializeApp } from“ www.example.com ”;从“www.example.com“导入{ getFirestore,collection,getDocs,onSnapshot,addDoc,deleteDoc,doc,getDoc,updateDoc,}https://www.gstatic.com/firebasejs/9.6.2/firebase-firestore.js;,它工作正常。但是我想从firebase/app而不是url使用。
链接到firebase的代码:

// Import the functions you need from the SDKs you need
import { initializeApp } from "node_modules/firebase/app";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import {
  getFirestore,
  collection,
  getDocs,
  onSnapshot,
  addDoc,
  deleteDoc,
  doc,
  getDoc,
  updateDoc,
} from "node_modules/firebase/firestore";

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};

// Initialize Firebase
export const app = initializeApp(firebaseConfig);

export const db = getFirestore();

export const saveTask = (title, description) =>
  addDoc(collection(db, "tasks"), { title, description });

export const onGetTasks = (callback) =>
  onSnapshot(collection(db, "tasks"), callback);

export const deleteTask = (id) => deleteDoc(doc(db, "tasks", id));

export const getTask = (id) => getDoc(doc(db, "tasks", id));

export const updateTask = (id, newFields) =>
  updateDoc(doc(db, "tasks", id), newFields);

export const getTasks = () => getDocs(collection(db, "tasks"));

Firestore目录:

以及节点模块内部:

f5emj3cl

f5emj3cl1#

您必须像这样导入它:

import { initializeApp } from 'firebase/app';
import { getFirestore, collection, getDocs } from 'firebase/firestore';
// ...

或者如果你使用普通的js:

const { initializeApp } = require('firebase/app');
const { getFirestore, collection, getDocs } = require('firebase/firestore');
// ...

只需从import语句中删除“node_modules/
See the package DOCs

c3frrgcw

c3frrgcw2#

需要将app传递给getFirestore函数,如下所示:

export const db = getFirestore(app);

相关问题