Last active
February 10, 2024 08:58
-
-
Save dyaa/8f8d1f8964160630f2475fe26a2e6150 to your computer and use it in GitHub Desktop.
Lazy Load Import Firebase (dynamic import)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Promise.all([ | |
import('firebase/app'), | |
import('firebase/database'), | |
import('firebase/auth'), | |
]) | |
.then(x => x[0].default) | |
.then(firebase => { | |
const config = { | |
apiKey: '', | |
authDomain: '', | |
databaseURL: '', | |
projectId: '', | |
storageBucket: '', | |
messagingSenderId: '', | |
} | |
firebase.initializeApp(config) | |
if (global.firebase) { | |
return global.firebase | |
} else if (!firebase) { | |
return Promise.reject(new Error('loading error')) | |
} else { | |
global.firebase = firebase | |
const googleAuthProvider = new firebase.auth.GoogleAuthProvider() | |
googleAuthProvider.addScope('https://www.googleapis.com/auth/userinfo.email') | |
global.firebase.googleAuthProvider = googleAuthProvider | |
return global.firebase ? global.firebase : firebase | |
} | |
}) | |
.catch(err => { | |
throw new Error(err) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@Jaseibert Thanks this works great.
To add on, I also made my own firebase types/interface files (I am using typescript), then I re-wrote firebase code I needed to use which I couldn't wait for (such as Timestamp) in my own files without the bloat. Lastly I made sure I absolutely never imported from
firebase/(any of them)
outside of the root firestore files were created from your guide.The second step of the optimization I explained above took and extra 125kB+ off the bundle. After optimizing just firebase my first load JS shared by all went from 320kB to 125kB! (I use functions, storage, firestore, and auth)
You can use this eslint rule to prevent importing firebase directly:
"no-restricted-imports": ["error", "firebase/app", "firebase/firestore", "firebase/storage", "firebase/auth", "firebase/functions"]