【发布时间】:2020-09-26 07:01:48
【问题描述】:
我希望我的 Firebase 管理项目中的多个函数具有相同的方法例如:“生成随机字母数字字符串”。因此,为了避免使用样板代码,我在该文件夹中创建了一个 Utils 文件夹和一个 utilityFunctions.ts 文件。该文件仅包含一个生成字母数字字符串的导出函数。我已使用 import 语句将该文件导入我的函数文件之一。
这是我的文件,其中包含预期的全局方法:src/Utils/utilityFunctions.ts
export const theRandomDocId = function randomDocumentId(length: number):
String {
// the code to generate a random string
}
这是我的一个函数文件:src/Compliment/addNewCompliment.ts
import * as functions from 'firebase-functions'
const admin = require('firebase-admin')
//This import statement below for the utilityFunctions file
import utilityFunctions = require('../Utils/utilityFunctions')
export const addTheNewCompliment = functions.region('asia-east2').https.onCall((complimentData,
context) => {
//generate random 11 alphanumeric ComplimentId converted to String
const randomComplimentId = utilityFunctions.theRandomDocId(28)
//There is a lot more code in this file but since its not relevant to the
//problem, I have excluded it.
}
这是 vs 代码显示的错误:
! functions[addNewCompliment(asia-east2)]: Deployment error.
Function failed on loading user code. Error message: Code in file lib/index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module '../Utils/utilityFunctions'
at Function.Module._resolveFilename (module.js:548:15)
at Function.Module._load (module.js:475:25)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/srv/lib/Compliment/addNewCompliment.js:5:26)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
我也尝试过在没有导出变量的情况下声明该方法,并在没有导入语句的情况下从我的 addNewCompliment.ts 文件中访问该方法,代码编译但是当它被触发时,Firebase 函数日志会引发错误:
Unhandled error ReferenceError: randomDocumentId is not defined
这是我的 package.json 文件
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase emulators:start --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"main": "lib/index.js",
"dependencies": {
"@google-cloud/storage": "^4.7.0",
"@types/sharp": "^0.25.0",
"child-process-promise": "^2.2.1",
"firebase-admin": "^8.9.0",
"firebase-functions": "^3.6.2",
"fs-extra": "^9.0.0",
"sharp": "^0.25.2"
},
"devDependencies": {
"tslint": "^5.12.0",
"typescript": "^3.2.2",
"firebase-functions-test": "^0.1.6"
},
"private": true
}
【问题讨论】:
-
您还记得include the local modules 作为部署包的一部分吗?如果您可以使用有关文件结构以及 package.json 文件的更多信息来更新问题,将会很有帮助。
-
嗨 pessolato,我已经用我的 package.json 文件更新了这个问题,我没有将本地模块作为部署包的一部分...当它添加到 package.json 文件时,我得到了这个错误:错误:找不到模块'../Utils/utilityFunctions'
-
嗨 pessolato,经过大量阅读和反复试验。我弄清楚了包含本地模块的工作原理......感谢您的评论,它为我指明了正确的方向......
标签: typescript firebase google-cloud-functions