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

妖精的绣舞 提交于 2019-12-11 15:54:01

问题


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 i.e.

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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/57391458/import-only-used-bits-from-firebase-admin-when-using-typescript-in-cloud-functio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!