Nuxt Load Firebase V9 Dynamically

April 12, 2022

I Nuxt With Firebase V9 Modular (Tree Shake), we load firebase application and analytics by default (static), but load other firebase modules like auth and firebase dynamically.

Here we will load everything dynamically.

Edit plugins/firebaseClient.js with the following modification.

import { initializeApp, getApps } from "firebase/app"
import { getAnalytics } from "firebase/analytics";

const firebaseConfig = {
  apiKey: "AIza******",
  authDomain: "*****.firebaseapp.com",
  projectId: "*****",
  storageBucket: "*****.appspot.com",
  messagingSenderId: "9613*****",
  appId: "1:9613*****:web:5ec9*****",
  measurementId: "G-C7*****"
}

export default async ({ app, store }, inject) => {
  const fire = {
    // app,
    // analytics,
    async getApp() {
      if (!this.app) {
        // const { initializeApp, getApps } = await import(
        //  /* webpackChunkName: "firebase" */ 
        //   "firebase/app")
        const apps = getApps()
        let firebaseApp = null
        if (!apps.length) {
          this.app = initializeApp(firebaseConfig)
        } else {
          this.app = apps[0]
        }
      }

      return this.app
    },
    async getAnalytics() {
      if (!this.analytics) {
        // const { getAnalytics } = await import(/* webpackChunkName: "firebase" */ "firebase/analytics");

        const firebaseApp = await this.getApp()
        this.analytics = getAnalytics(firebaseApp);
      }

      return this.analytics
    }
  }

  inject('fire', fire)

  if (process.env.NODE_ENV == 'production') {
    // if (isMobile()) {
      // delay loading analytics
      setTimeout(async () => {
        await fire.getAnalytics()
      }, 5000)
    // }
    //else {
    //  await fire.getAnalytics();
    //}
  }
}

If you want to optimize the default bundle size further, you can also perform dynamic import.

// import { initializeApp, getApps } from "firebase/app"
// import { getAnalytics } from "firebase/analytics";
const fire = {
  async getApp() {
    if (!this.app) {
      const { initializeApp, getApps } = await import(
        /* webpackChunkName: "firebase" */ 
        "firebase/app")
      const apps = getApps()
      let firebaseApp = null
      if (!apps.length) {
        this.app = initializeApp(firebaseConfig)
      } else {
        this.app = apps[0]
      }
    }

    return this.app
  },
  async getAnalytics() {
    if (!this.analytics) {
      const { getAnalytics } = await import(/* webpackChunkName: "firebase" */ "firebase/analytics");

      const firebaseApp = await this.getApp()
      this.analytics = getAnalytics(firebaseApp);
    }

    return this.analytics
  }
}

NOTE: JavaScript Dynamic Import with Tree Shaking (via async).

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.