简体   繁体   中英

Importing firebase from node_modules not working

I have created a folder in htdocs directory named firestore, and using cmd to install npm firebase in firestore directory. It generates package.json, package-lock.json and node_modules. I want to link to firebase but it is not working. I take away the firebaseconfig key for privacy reasons and yes, I did create a firestore database project in firebase. When I use import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.2/firebase-app.js"; and import { getFirestore, collection, getDocs, onSnapshot, addDoc, deleteDoc, doc, getDoc, updateDoc, } from "https://www.gstatic.com/firebasejs/9.6.2/firebase-firestore.js"; , it is working fine. However I want to use from firebase/app instead of url.

Code that links to 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 directory: 在此处输入图像描述

and inside node_modules: 在此处输入图像描述

You have to import it like this:

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

or like so if you use common js:

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

Just remove "node_modules/" from the import statement

See the package DOCs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM