首页 > 解决方案 > 如何在 Firebase Cloud Functions 中捆绑和要求非 JS 依赖项?

问题描述

我有一个返回一些动态 HTML 的 http 云函数。我想使用 Handlebars 作为模板引擎。const模板足够大,将它放在我的函数顶部的变量中是不切实际的。

我试过类似的东西:

const template = fs.readFileSync('./template.hbs', 'utf-8');

但是在部署该功能时,我总是收到文件不存在的错误:

Error: ENOENT: no such file or directory, open './template.hbs'

template.hbs与我的文件在同一个目录中,index.js所以我想问题是 Firebase CLI 没有将此文件与其余文件捆绑在一起。

根据Google Cloud Functions 的文档,可以将本地模块与"mymodule": "file:mymodule". 所以我尝试templates在项目的根目录创建一个文件夹并添加"templates": "file:./templates"package.json.

我的文件结构是这样的:

/my-function
  index.js
/templates
  something.hbs
index.js //this is the entry point

接着:

const template = fs.readFileSync('../node_modules/templates/something.hbs', 'utf-8');

但我得到了同样的未找到错误。

在 Firebase Cloud Function 中包含和要求非 JS 依赖项的正确方法是什么?

标签: node.jsfirebasegoogle-cloud-functions

解决方案


Firebase CLI 将打包您的函数文件夹中的所有文件,除了 node_modules,并将整个存档发送到 Cloud Functions。它将通过npm install在构建运行您的函数的 docker 映像时运行来重构 node_modules。

如果您的 something.hbs 位于您的函数文件夹下的 /templates 中,您应该能够./templates/something.hbs从顶级 index.js 中引用它。如果您的 JS 在另一个文件夹中,您可能必须先使用../templates/something.hbs. 文件应该都在那里——只要找出路径。我不会尝试做任何花哨的事情是你的 package.json。只需利用 CLI 部署除 node_modules 之外的所有内容这一事实。

如果我的函数文件夹的根目录中有一个名为“foo”的文件,那么这段代码对我来说很好:

import * as fs from 'fs'
export const test = functions.https.onRequest((req, res) => {
    const foo = fs.readFileSync('./foo', 'utf-8')
    console.log(foo)
    res.send(foo)
})

推荐阅读