1

Right now I'm doing:

firebase.js

import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/functions';
import 'firebase/storage';

const config = {
  apiKey: process.env.FIREBASE_APP_API_KEY,
  authDomain: process.env.FIREBASE_APP_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_APP_DATABASE_URL,
  projectId: process.env.FIREBASE_APP_PROJECT_ID,
  storageBucket: process.env.FIREBASE_APP_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_APP_MESSAGING_SENDER_ID,
  appId: process.env.FIREBASE_APP_ID,
};

firebase.initializeApp(config);

export default firebase;

webpack.config.js

optimization: {
  runtimeChunk: 'single',
  splitChunks: {
    chunks: 'all',
    maxInitialRequests: Infinity,
    minSize: 0,
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name(module) {
          const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
          return `npm.${packageName.replace('@', '')}`;
        },
      },
    },
  },
}

The webpack part I got from this article:

https://medium.com/hackernoon/the-100-correct-way-to-split-your-chunks-with-webpack-f8a9df5b7758

And this results in this small 667kb JS file (this is the production version):

enter image description here

QUESTION

CanI import it in some other way so I could end up with smaller chunks?

For example:

import firebase from 'firebase/app';
import auth from 'firebase/auth';
import firestore from 'firebase/firestore';
import functions from 'firebase/functions';
import storage from 'firebase/storage';

But I have no idea what I'm going to do with those "extra objects", since the only one I need and use is the firebase object that I get from firebase/app

Also, if I import them like this and don't use the objects, wouldn't Webpack interpret them as "dead code" and tree shake them?

What's is the proper way to do this?

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336

1 Answers1

0

Firebase loads these imports directly into the firebase object, there's no way to treeshake them from there. What you can do is optionally load these with dynamic import, webpack will then take care of codesplitting these. If not imported, these instances are not added to the firebase object so you can do a simple if check to load them in.


export async function getFirestoreInstance() {
    if (!firebase.firestore) {
        await import('firebase/firestore');
    }

    return firebase.firestore();
}

When you need to use Firestore for example, simply call getFirestoreInstance

async function doSomethingWithFirestore(){
   try {
      const firestore = await getFirestoreInstance();
      firestore.collection("foo") // do something with firestore
   }
}
Chief koshi
  • 257
  • 3
  • 7