【发布时间】:2019-09-15 14:36:56
【问题描述】:
我在 React 应用程序中使用 Firebase 函数。我有一些我不想复制的重要代码,所以我想在部署的函数和我的 React 客户端之间共享它。我已经在我的 React 客户端本地工作了(虽然我没有尝试过部署) - 但我无法部署我的功能。
我尝试的第一件事是 npm 链接。这在本地工作,但函数不会部署(这是有道理的,因为这不会在您的 package.json 中留下任何依赖关系)。然后我尝试了 npm install ../shared/ - 这看起来很有希望,因为它确实在 package.json 中留下了一个带有 file: 前缀的依赖项 - 但 Firebase 仍然不会使用它进行部署(以下错误)。
我的项目目录结构如下:
/ProjectDir
firebase.json
package.json (for the react app)
/src
* (react source files)
/functions
package.json (for firebase functions)
index.js
/shared
package.json (for the shared module)
index.js
我的共享模块 package.json(无关细节省略):
{
"name": "myshared",
"scripts": {
},
"dependencies": {
},
"devDependencies": {
},
"engines": {
"node": "8"
},
"private": true,
"version": "0.0.1"
}
我的 firebase 函数 package.json(无关细节省略):
{
"name": "functions",
"scripts": {
},
"dependencies": {
"myshared": "file:../shared",
},
"devDependencies": {
},
"engines": {
"node": "8"
},
"private": true
}
当我尝试部署时:
firebase deploy --only functions
它告诉我它无法加载模块:
Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
而且我认为问题不在于我如何导出/导入我的代码——但以防万一: 出口:
exports.myFunc = () => { some code };
导入(functions/index.js)
const myFunc = require('myshared');
在我的反应代码中:
import { myFunc } from 'myshared';
到目前为止,我所做的搜索还没有产生任何有用的东西。有人确实提到在 firebase.json 中输入共享模块路径,但我找不到任何细节(包括在 firebase 文档中)来显示它的样子。感谢您提供任何提示。
【问题讨论】:
-
仅供参考 - 当您部署到 Cloud Functions 时,您不能引用
functions之外的任何内容。整个文件夹将在部署时打包,除了 node_modules。所以,当npm install重建你的后端时,你提供的任何东西都需要在那里访问。 -
是的,我发现了 =) 实际上我找到了一种方法来完成这项工作。不确定它是否是最好的方法,但我会在下面发布。谢谢!
标签: node.js reactjs firebase google-cloud-functions