Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic loading of firebase modules? (v9)

I am using the newest Firebase version 9 and I was trying to optimize loading times. One way could be to dynamically load the firebase modules only when they are needed instead of waiting for all of them to be loaded. For example importing the signOut() function from 'firebase/auth' only when the user clicks the sign out button. Would this strategy work? I am strugling to implement it on firebase 9. Are there any examples available?

So far I have tried:

index.js: the below code didn't work, aparently webpack could't compile (error: The top-level-await experiment is not enabled)

let {signOut, signInAnonymously, etc.} = await import('firebase/auth');
like image 866
blu potatos Avatar asked Sep 17 '25 17:09

blu potatos


2 Answers

I had a similar problem with lazy loading only Firestore. Usually, I don't need to load Firestore for every page as pages are SSR, the only time I need Firestore is when the user clicks "Load more".

I managed to do that with the code below (Firebase V9):

let database = null;

async function loadFirestore() {
  if (!database) {
    const { initializeApp } = await import('firebase/app');
    const { getFirestore } = await import('firebase/firestore');
    const app = initializeApp(firebaseConfig);
    database = getFirestore(app);
  }

  return database;
}

export { loadFirestore };

And then on my page:

const db = await loadFirestore();
const videoRef = doc(db, 'collection-name', id);
like image 107
Andurit Avatar answered Sep 20 '25 05:09

Andurit


The error message is pretty clear: unless you explicitly allow it in your webpack config, the await keyword cannot be used in top-level code.

That said, you don't need await on an import statement, as this is handled synchronously during the build already. As shown in the example in the Firebase documentation like:

import { getAuth, signInAnonymously } from "firebase/auth";

So in your case, use:

import { signOut, signInAnonymously } from 'firebase/auth');
like image 29
Frank van Puffelen Avatar answered Sep 20 '25 07:09

Frank van Puffelen