0
0
Firebasecloud~5 mins

Modular SDK (v9+) tree-shaking in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
When you build apps with Firebase, you want your app to load fast and use less data. The Modular SDK version 9 helps by letting you include only the parts you need. This makes your app smaller and quicker.
When you want your Firebase app to load faster on slow internet connections.
When you want to reduce the size of your app to save users' data.
When you are building a web app and want to include only the Firebase features you use.
When you want to avoid loading unnecessary Firebase code that your app does not need.
When you want to improve your app's performance by using modern JavaScript imports.
Commands
This command installs the latest stable Firebase Modular SDK version 9.22.1 in your project to use tree-shaking features.
Terminal
npm install firebase@9.22.1
Expected OutputExpected
+ firebase@9.22.1 added 1 package from 1 contributor and audited 1 package in 1.234s found 0 vulnerabilities
This command checks that you can import only the needed Firebase functions using the Modular SDK syntax.
Terminal
node -e "import('firebase/app').then(({ initializeApp }) => console.log(typeof initializeApp))"
Expected OutputExpected
function
This command runs your build process (like with Webpack or Vite) which removes unused Firebase code thanks to tree-shaking.
Terminal
npm run build
Expected OutputExpected
[webpack] Hash: abc123 Version: 5.0.0 Built at: 2024-06-01 12:00:00 Asset Size Chunks Chunk Names main.js 50 KiB main [emitted] main WARNING in asset size limit: The following asset(s) exceed the recommended size limit (244 KiB).
Key Concept

If you remember nothing else from this pattern, remember: import only the Firebase functions you use to keep your app small and fast.

Common Mistakes
Importing the entire Firebase SDK using 'import firebase from "firebase";'
This loads all Firebase features, making your app large and slow to load.
Use modular imports like 'import { initializeApp } from "firebase/app";' to include only what you need.
Using old Firebase namespaced syntax with Modular SDK v9+
The old syntax is not tree-shakeable and can cause errors or bigger bundles.
Use the new Modular SDK syntax with direct function imports.
Summary
Install Firebase Modular SDK version 9 to enable tree-shaking.
Import only the Firebase functions your app uses with modular import syntax.
Run your build tool to remove unused Firebase code and reduce app size.