Using module bundlers with Firebase Stay organized with collections Save and categorize content based on your preferences.
JavaScript module bundlers can do many things, but one of their most usefulfeatures is the ability to add and use external libraries in your code base.Module bundlers read import paths in your code and combine (bundle) yourapplication-specific code with your imported library code.
From version 9 and higher, the Firebase JavaScript modular APIis optimized to work with theoptimization features of module bundlers to reduce the amount of Firebase codeincluded in your final build.
import{initializeApp}from'firebase/app';import{getAuth,onAuthStateChanged,getRedirectResult}from'firebase/auth';constfirebaseApp=initializeApp({/* config */});constauth=getAuth(firebaseApp);onAuthStateChanged(auth,user=>{/* check status */});/** * getRedirectResult is unused and should not be included in the code base. * In addition, there are many other functions within firebase/auth that are * not imported and therefore should not be included as well. */This process of eliminating unused code from a library is known as tree shaking.It would be extremely time consuming and error prone to manually remove thiscode by hand, but module bundlers can automate this removal.
There are many high quality module bundlers in the JavaScript ecosystem. Thisguide is focused on covering using Firebase withwebpack,Rollup, andesbuild.
Get started
This guide requires you to have npm installed in your development environment.npm is used to install and manage dependencies (libraries). To install npm,install Node.js, which includesnpm automatically.
Most developers are properly set up once they have installed Node.js. However,there are common problems many developers run into when setting up theirenvironment. If you run into any errors,make sure your environment has the npm CLI and that you have the proper permissions set up so youdon't have to install packages as an administrator with the sudo command.
package.json and installing Firebase
Once you have npm installed you will need to create apackage.json file at theroot of your local project. Generate this file with the following npm command:
npminitThis will take you through a wizard to supply the needed information. Once thefile is created it will look similar to the following:
{"name":"your-package-name","version":"1.0.0","description":"","main":"index.js","scripts":{"test":"echo \"Error: no test specified\" && exit 1"},"keywords":[],"author":"","license":"ISC","dependencies":{}}This file is responsible for many different things. This is an important file tofamiliarize yourself with if you want to learn more about module bundling andbuilding JavaScript code in general. The important piece for this guide is the"dependencies" object. This object will hold a key value pair of the libraryyou have installed and the version it is using.
Adding dependencies is done through thenpm install ornpm i command.
npmifirebaseWhen you runnpm i firebase, the installation process will updatepackage.json to list Firebase as a dependency:
"dependencies":{"firebase":"^9.0.0"},The key is the name of the library and the value is the version to use. Theversion value is flexible and can accept a range of values. This is known assemantic versioning or semver. To learn more about semver,see npm's guide about semantic versioning.
Source vs build folders
The code you write is read and processed by a module bundler and then output asa new file or set of files. It's important to separate these two types of files.The code the module bundlers read and process is known as "source" code. Thefiles they output are known as the built or "dist" (distribution) code.
A common setup in code bases is to store source code in a folder calledsrcand the built code in a folder nameddist.
- src |_ index.js |_ animations.js |_ datalist.js- dist |_ bundle.jsIn the example file structure above, consider thatindex.js imports bothanimations.js anddatalist.js. When a module bundler processes the sourcecode it will produce thebundle.js file in thedist folder. Thebundle.jsis a combination of the files in thesrc folder and any libraries the importas well.
If you are using source control systems such as Git, it is common to ignore thedist folder when storing this code in the main repository.
Entry points
Module bundlers all have a concept of an entry point. You can think of yourapplication as a tree of files. One file imports code from another and so on andso forth. This means that one file will be the root of the tree. This file isknown as the entry point.
Let's revisit the previous file structure example.
- src |_ index.js |_ animations.js |_ datalist.js- dist |_ bundle.js// src/index.jsimport{animate}from'./animations';import{createList}from'./datalist';// This is not real code, but for example purposes onlyconsttheList=createList('users/123/tasks');theList.addEventListener('loaded',event=>{animate(theList);});Thesrc/index.js file is considered the entry point because it begins theimports of all the needed code for the application. This entry point file isused by module bundlers to begin the bundling process.
Using Firebase with webpack
There is no specific configuration needed for Firebase apps and webpack. Thissectioncovers a general webpack configuration.
The first step is to install webpack from npm as a development dependency.
npmiwebpackwebpack-cli-DCreate a file at the root of your local project namedwebpack.config.js andadd the following code.
constpath=require('path');module.exports={// The entry point file described aboveentry:'./src/index.js',// The location of the build folder described aboveoutput:{path:path.resolve(__dirname,'dist'),filename:'bundle.js'},// Optional and for development only. This provides the ability to// map the built code back to the original source format when debugging.devtool:'eval-source-map',};Then make sure you have Firebase installed as a dependency.
npmifirebaseThen initialize Firebase in your code base. The following code imports andinitializes Firebase in an entry point file and uses Firestore Lite to load a"city" document.
// src/index.jsimport{initializeApp}from'firebase/app';import{getFirestore,doc,getDoc}from'firebase/firestore/lite';constfirebaseApp=initializeApp({/* config */});constdb=getFirestore(firebaseApp);asyncfunctionloadCity(name){constcityDoc=doc(db,`cities/${name}`);constsnapshot=awaitgetDoc(cityDoc);return{id:snapshot.id,...snapshot.data(),};}The next step is toadd an npm script to run the webpack build. Open thepackage.json fileand add the following key value pair to the"scripts" object.
"scripts":{"build":"webpack --mode=development"},To run webpack and generate the build folder run the following command.
npmrunbuildFinally, check thedist build folder. It should contain a file namedbundle.js that contains your bundled application and dependency code.
For more information on optimizing your webpack build for production, see theirofficial documentation onthe "mode" configuration setting.
Using Firebase with Rollup
There is no specific configuration needed for Firebase apps and Rollup. Thissection covers a general Rollup configuration.
The first step is to install Rollup and a plugin used to map imports todependencies installed with npm.
npmirollup@rollup/plugin-node-resolve-DCreate a file at the root of your local project namedrollup.config.js and addthe following code.
import{nodeResolve}from'@rollup/plugin-node-resolve';exportdefault{// the entry point file described aboveinput:'src/index.js',// the output for the build folder described aboveoutput:{file:'dist/bundle.js',// Optional and for development only. This provides the ability to// map the built code back to the original source format when debugging.sourcemap:'inline',// Configure Rollup to convert your module code to a scoped function// that "immediate invokes". See the Rollup documentation for more// information: https://rollupjs.org/guide/en/#outputformatformat:'iife'},// Add the plugin to map import paths to dependencies// installed with npmplugins:[nodeResolve()]};Then initialize Firebase in your code base. The following code imports andinitializes Firebase in an entry point file and uses Firestore Lite to load a"city" document.
// src/index.jsimport{initializeApp}from'firebase/app';import{getFirestore,doc,getDoc}from'firebase/firestore/lite';constfirebaseApp=initializeApp({/* config */});constdb=getFirestore(firebaseApp);asyncfunctionloadCity(name){constcityDoc=doc(db,`cities/${name}`);constsnapshot=awaitgetDoc(cityDoc);return{id:snapshot.id,...snapshot.data(),};}The next step is toadd an npm script to run the rollup build. Open thepackage.json fileand add the following key value pair to the"scripts" object.
"scripts":{"build":"rollup -c rollup.config.js"},To run rollup and generate the build folder, run the following command.
npmrunbuildFinally, check thedist build folder. It should contain a file namedbundle.js that contains your bundled application and dependency code.
For more information on optimizing your Rollup build for production, see theirofficial documentationon plugins for production builds.
Using Firebase with esbuild
There is no specific configuration needed for Firebase apps and esbuild. Thissection covers a general esbuild configuration.
The first step is to install esbuild as a development dependency.
npmiesbuild-DCreate a file at the root of your local project namedesbuild.config.js andadd the following code.
require('esbuild').build({// the entry point file described aboveentryPoints:['src/index.js'],// the build folder location described aboveoutfile:'dist/bundle.js',bundle:true,// Replace with the browser versions you need to targettarget:['chrome60','firefox60','safari11','edge20'],// Optional and for development only. This provides the ability to// map the built code back to the original source format when debugging.sourcemap:'inline',}).catch(()=>process.exit(1))Then initialize Firebase in your code base. The following code imports andinitializes Firebase in an entry point file and uses Firestore Lite to load a"city" document.
// src/index.jsimport{initializeApp}from'firebase/app';import{getFirestore,doc,getDoc}from'firebase/firestore/lite';constfirebaseApp=initializeApp({/* config */});constdb=getFirestore(firebaseApp);asyncfunctionloadCity(name){constcityDoc=doc(db,`cities/${name}`);constsnapshot=awaitgetDoc(cityDoc);return{id:snapshot.id,...snapshot.data(),};}The next step is toadd an npm script to run esbuild. Open thepackage.json file and addthe following key value pair to the"scripts" object.
"scripts":{"build":"node ./esbuild.config.js"},Finally, check thedist build folder. It should contain a file namedbundle.js that contains your bundled application and dependency code.
For more information on optimizing esbuild for production, see their officialdocumentationon minification and other optimizations.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2026-02-05 UTC.