简体   繁体   中英

How to import module based dependencies for firebase cloud functions?

I want to organize my firebase cloud functions in specific files, and currently, I have these 3:

  • index.ts
  • crypto.ts
  • webscrape.ts

Inside of these files, I have functions that use specific dependencies that are needed nowhere else.

For example, in crypto.ts I need the crypto-js package to encrypt some user data and store it into the database.

So I am importing it like so:

 import * as CryptoJS from "crypto-js";

as advised in https://firebase.google.com/docs/functions/handle-dependencies#typescript


On the other hand, when I try to import puppeteer into webscrape.ts like this:

 import * as puppeteer from"puppeteer-extra";

then calling puppeteer.launch(); gives me an error:

Property 'launch' does not exist on type 'typeof import("c:/Users/username/Desktop/project/firebasee/functions/node_modules/puppeteer-extra/dist/index ")'

and it only works when I do const puppeteer = require("puppeteer-extra");

What's the difference here?


My goal is to keep the dependencies of each functions and file/module as small as possible because I assume that this will also keep the size of each function container small (Is that even true?)

I didn't want to import everything to index.ts even when I trigger a function, that doesn't use this dependency at all.

So what is the correct way of handling these dependencies?

Thanks!

The following import will get the default export from that package.

import puppeteer from "puppeteer-extra"

I looked for the default export in the Github repository and found that.

const defaultExport: PuppeteerExtra = (() => {
  return new PuppeteerExtra(...requireVanillaPuppeteer())
})()

export default defaultExport

They have mentioned both ES6 import and require methods here .

// javascript import
const puppeteer = require('puppeteer-extra')

// typescript/es6 module import
import puppeteer from 'puppeteer-extra'

You can read more about import on MDN .

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