Justin
Justin

Reputation: 1059

Firestore onSnapshot - firebase.firestore is not a function - Failed to resolve module specifier "firebase"

I'm just trying to learn firebase, and I wanted to use onSnapshot so switched from "realtime database" to "firestore". After switching I copied this boilerplate code:

document.addEventListener("DOMContentLoaded", evt=> {
  const app = firebase.app();
  const db = firebase.firestore();

  db.collection('users')
    .onSnapshot((snapshot) => {
      console.log(`Received doc snapshot: ${snapshot}`);
    }, (error) => {
      console.log(`Encountered error: ${error}`);
    });

});

However I got that "firebase.firestore is not a function". I found the solution here: https://stackoverflow.com/a/50684682/4907950 which is just adding:

import * as firebase from 'firebase';
import 'firebase/firestore';

However, then I get: "Uncaught TypeError: Failed to resolve module specifier "firebase". Relative references must start with either "/", "./", or "../"."

EDIT: Also worth noting that I've added <script defer src="/__/firebase/7.14.2/firebase-firestore.js"></script> to my HTML file and the error persists.

Upvotes: 0

Views: 2664

Answers (2)

Dharmaraj
Dharmaraj

Reputation: 50840

For some reason I had to use the complete URL and keep them at top of <BODY> tag like this:

<body>
  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-auth.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-database.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-messaging.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-storage.js"></script>

  <script src="app.js"></script>
</body>

Also I had to re-install all requires stuff using Firebase CLI. It worked perfectly thereafter.

Upvotes: 1

Justin
Justin

Reputation: 1059

Removing:

import * as firebase from 'firebase';
import 'firebase/firestore';

From the stackoverflow post I had found, while keeping the firestore link seemed to do the trick.

Upvotes: 1

Related Questions