如何在 ES6 语法中导入 firebase-functions 和 firebase-admin 以使用 Babel for Node 10 进行转译

cbd*_*per 5 javascript node.js firebase google-cloud-functions firebase-admin

我目前正在 ES6 中编写我的云函数,并使用 Babel 进行转换以针对 Node v10 环境。而且我注意到了一些奇怪的事情。

为什么当我这样导入时firebase-functions

import functions from 'firebase-functions';

我收到此错误:

!  TypeError: Cannot read property 'https' of undefined
    at Object.<anonymous> (C:\myProject\functions\index.js:28:55)
Run Code Online (Sandbox Code Playgroud)

为了修复它,我需要像这样导入它:

import * as functions from 'firebase-functions';

虽然以下import适用于firebase-admin

import admin from 'firebase-admin';

简而言之,问题是:

这是为什么:

import functions from 'firebase-functions';            // DOESN'T WORK
import * as functions from 'firebase-functions';       // WORKS
import admin from 'firebase-admin';                    // WORKS
Run Code Online (Sandbox Code Playgroud)

sll*_*pis 8

import functions from 'firebase-functions';无法工作的原因是因为'firebase-functions'没有“函数”默认导出。

因此,这个错误:

!  TypeError: Cannot read property 'https' of undefined
    at Object.<anonymous> (C:\myProject\functions\index.js:28:55)
Run Code Online (Sandbox Code Playgroud)

解决方案:

第一个选项是导入整个模块的内容并将其添加functions到包含模块所有导出的当前范围中firebase-functions

import * as functions from 'firebase-functions'
Run Code Online (Sandbox Code Playgroud)

第二个选择是从一个模块导入单个出口,https在这种情况下,因为你试图读取属性https'firebase-functions'

import { https } from 'firebase-functions'
Run Code Online (Sandbox Code Playgroud)

可以在此处找到更多信息。

希望这能澄清你的问题。