Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite firebase service using dynamic import

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();
  });
like image 820
Sunrise Avatar asked May 29 '18 15:05

Sunrise


1 Answers

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 };
like image 151
João Melo Avatar answered Nov 19 '22 19:11

João Melo