Please help me to rewrite the code to use the dynamic import feature. Unfortunately i have no idea how to use dynamic import in module.
import firebase from 'firebase/app';
import 'firebase/firestore';
const config = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
};
const initApp = firebase.initializeApp(config).firestore();
initApp.settings({
timestampsInSnapshots: true,
});
const app = firebase.app().firestore();
export default !firebase.apps.length ? initApp : app;
What i tried
import('firebase/app')
.then((firebase) => {
firebase.initializeApp(config).firestore();
});
That's because the firebase variable you want is in fact inside a default property. You could do something like this:
import('firebase/app')
.then(firebase => {
firebase.default.initializeApp(config).firestore();
});
A complete suggestion with async functions bellow:
// firebase-service.js
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MSG_SENDER_ID,
appId: process.env.FIREBASE_APP_ID
};
let db;
async function getFirestore () {
if (!db) {
const { default: firebase } = await import('firebase/app');
await import('firebase/firestore');
const app = firebase.initializeApp(firebaseConfig);
db = app.firestore();
}
return db;
}
export { getFirestore };
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