简体   繁体   中英

Import only used bits from firebase-admin when using Typescript in Cloud Functions

I glanced at my transpiled code from cloud functions and following typescript import

import { auth, firestore } from 'firebase-admin';

is transpiled to

const firebase_admin_1 = require("firebase-admin");

Looking at this it imports whole admin library as opposed to just bits I need and I assume this will contribute to bigger cold start times.

I tried to require these in my ts code using require ie

const { auth, firestore } = require('firebase-admin');

but doing so makes it loose it's type definitions.

I wanted to ask if there is a way to use only what I need from firebase-admin lib, without compromising typescript definitions?

In case of firebase-admin such a thing is not mentioned in the docs, since firebase-admin sdk is meant for the server side of things.

But there is definitely one for firebase client sdk.

const firebase = require('firebase/app'); require('firebase/auth'); require('firebase/firestore');

And I think by the look of your question you need the client sdk.

When you require('firebase-admin') (or import in TypeScript, it's the same thing), it doesn't matter what symbols you import into your code. The same thing will happen regardless - the entire module will be loaded. Importing individual symbols from the library does not change this fact, it just changes which symbols you have available in your code. If you are trying to optimize your code by only choosing certain symbols to import, that's not really a valid optimization in JavaScript. All you can really do is not use the parts of the SDK that you don't need.

firebase-admin is a monolithic package. It just exports a single entity; namely the admin namespace. Therefore it's not possible to import just bits and pieces of it. However, the package also implements a bunch of lazy loading stuff internally, which make sure that only the things that developers use get loaded.

const admin = require('firebase-admin');
// The admin namespace is now loaded. But none of the API services 
// haven't loaded yet.

admin.auth();
// This loads the Auth service code, and any dependencies it uses.

admin.firestore();
// This loads the @google-cloud/firestore package.

In an environment like Cloud Functions, this makes sure that the package only loads the necessary source files and dependencies. So you should simply import the admin namespace, and call methods on it and let the SDK import the necessary services/components on-demand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM