Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Failed to resolve module specifier "firebase/app"

it's my firstime using Firebase and I think that I've followed all step to connect my project to firebase. I tried to run my project with a small js console.log(firebase) When I went to my console I received this error message Failed to resolve module specifier "firebase/app"

I want to mention that I've create a node_module folder and I did npm i firebase.

html file:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>TP1</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/css/bulma.min.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
        <script type="module" src="/index.js"> </script>
    </head>
    <body>

index.js:

import { initializeApp } from "firebase/app";
//import { getDatabase } from "firebase/database";

const firebaseConfig = {
  //(my config...)
};


const app = initializeApp(firebaseConfig);
//const database = getDatabase(firebaseConfig);

console.log(firebase)
like image 633
MrBigboka Avatar asked Apr 15 '26 01:04

MrBigboka


2 Answers

To run Firestore without Webpack or Rollup, skip the npm installs and replace the import lines with Firestore's browser module references. It's explained here:

https://firebase.google.com/docs/web/setup?sdk_version=v9&authuser=0 (in Step 2).

The video is helpful as well, and it explains Firebase's new (in V9) modular/functional vs. the deprecated object.method model.

Here's how my JS module for the Firestore connection to a web app I've developed for work:

// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.1/firebase-app.js";
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.1.1/firebase-firestore.js"
import { collection, getDocs, addDoc, Timestamp } from "https://www.gstatic.com/firebasejs/9.1.1/firebase-firestore.js"
import { query, orderBy, limit, where, onSnapshot } from "https://www.gstatic.com/firebasejs/9.1.1/firebase-firestore.js"
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxx.firebaseapp.com",
projectId: "xxxx9",
storageBucket: "xxxxx.appspot.com",
messagingSenderId: "xxxxx",
appId: "1:xxx:web:xxx"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

export { app, db, collection, getDocs, Timestamp, addDoc };
export { query, orderBy, limit, where, onSnapshot };
like image 127
RobGH999 Avatar answered Apr 16 '26 14:04

RobGH999


When you use import { ... } from "some/package", you are expected to use a bundler like Webpack or Rollup to compile your code prior to accessing it on a website. This pulls the pieces you need out from your dependencies ready for use by your code.

Especially in v9+ of the SDK, the Firebase SDK was rewritten to support these bundlers, so expect many code examples you see to have been written for the now deprecated v8 or older. How to move this older code is covered in this migration guide.

A key takeaway from that guide is that firebase is no longer a global object. As you are new to Firebase, I would avoid writing any code that uses the old syntax. You can spot older syntax by looking for code like firebase.initializeApp(), firebase.database(), firebase.firestore() and so on. In the SDK those examples have been replaced by initializeApp(), getDatabase() and getFirestore() respectively.

If you intend to use modular code directly in your browser (using <script type="module" src="..."></script>), it is important to remember that the code is isolated from the browser console - you can't run console.log(firebaseConfig) and expect it to have your object.

This next section is not for production code, just for trying things out in a familiar environment.

If you want to tinker around with the Firebase libraries in your browser console, you will add something similar to this:

<script type="module">
  window.FIREBASE_MODULES = window.FM = {};

  async function loadFirebaseModule(serviceName, sinkErrors) {      
    const name = serviceName.toLowerCase();
    if (window.FIREBASE_MODULES[name]) return window.FIREBASE_MODULES[name];
      
    try {
      // uses unpkg to get the latest semver
      if (!loadFirebaseModule.version) {
        const response = await fetch("https://unpkg.com/firebase/firebase-app.js", { method: "HEAD" });
        const match = /@\d+(?:\.\d+)*/.exec(response.url);
        if (!match) {
          console.log("Unexpected resource URL (SemVer could not be determined, falling back to v9.0.0): " + response.url);
          loadFirebaseModule.version = "9.0.0";
        } else {
          loadFirebaseModule.version = match[0].slice(1);
        }
      }
      
      // use the found semver to pull from Google's CDN
      const module = await import(`https://www.gstatic.com/firebasejs/${loadFirebaseModule.version}/firebase-${name}.js`);
      window.FIREBASE_MODULES[name] = module;
        
      console.log(`Successfully imported "${name}" module`)
      return module;
    } catch (err) {
      if (sinkErrors) {
        console.error(`Failed to import "${name}" module`, err);
      } else {
        throw err;
      }
    }
  }
  window.loadFirebaseModule = loadFirebaseModule;
</script>

That little snippet will now allow you to run code like this either in-page or in the browser's console. It returns a Promise, so make sure to wait for it to finish resolving if you are using it inside a script.

loadFirebaseModule('app')
  .then(({ initializeApp }) => {
    initializeApp({ /* ... config ... */ });
  });

loadFirebaseModule('storage');
loadFirebaseModule('storage', true); // import & ignore the error

Once a module is loaded, you can use const { getApp } = FM.app similar to how you would use import { getApp } from "firebase/app".

like image 32
samthecodingman Avatar answered Apr 16 '26 16:04

samthecodingman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!