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');
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);
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With