Rewrite firebase service using dynamic import
Asked Answered
B

1

7

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();
  });
Bustamante answered 29/5, 2018 at 15:54 Comment(0)
V
2

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 };
Vocabulary answered 21/4, 2020 at 13:33 Comment(1)
How would you implement the same thing with Firebase 9 with imports like: import { getFirestore } from 'firebase/firestore';Caines

© 2022 - 2024 — McMap. All rights reserved.