JavaScript Dynamic Import with Tree Shaking (via async)

April 12, 2022

Static import

import { initializeApp, getApps } from "firebase/app"

Dynamic import

async getApp() {
  const { initializeApp, getApps } = await import("firebase/app")

  const apps = getApps()
  let firebaseApp = null
  let app = null
  if (!apps.length) {
    app = initializeApp(firebaseConfig)
  } else {
    app = apps[0]
  }

  return app 
}

Based on The unexpected impact of dynamic imports on tree shaking and this, seems like dynamic import doesn’t support tree-shaking.

Alternative solution is create a local module, edit localFirebase.js.

export { initializeApp, getApps } from "firebase/app"

Then

const { initializeApp, getApps } = await import("localFirebase.js")
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.