NodeJS(Firebase):无法导入自定义类

时间:2018-01-18 00:05:52

标签: javascript node.js firebase google-cloud-functions

我正在使用Firebase服务器端代码来发送推送通知。为了使代码干净,我决定将一些函数移动到我创建的另一个类,并调用notificationFunctions.js

当我在const notificationFunctions = require('notificationFunctions');顶部index.js并在我的sendNotification函数中调用该函数时,在将项目部署到云时出现错误:

⚠  functions[sendNotifications]: Deployment error.
Build failed: exit status 1
npm ERR! Linux 4.4.0-108-generic
npm ERR! argv "/nodejs/bin/node" "/nodejs/bin/npm" "--global-style" "--production" "--fetch-retries=5" "--fetch-retry-factor=2" "--fetch-retry-mintimeout=1000" "install" "/workspace"
npm ERR! node v6.11.5
npm ERR! npm  v3.10.10
npm ERR! code E404

npm ERR! 404 Registry returned 404 for GET on https://registry.npmjs.org/notificationFunctions
npm ERR! 404 
npm ERR! 404  'notificationFunctions' is not in the npm registry.
npm ERR! 404 Your package name is not valid, because 
npm ERR! 404  1. name can no longer contain capital letters
npm ERR! 404 It was specified as a dependency of 'functions'
npm ERR! 404 
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! Please include the following file with any support request:
npm ERR!     /workspace/npm-debug.log



Functions deploy had errors. To continue deploying other features (such as database), run:
    firebase deploy --except functions

我还在"notificationFunctions": "1.0.0"中添加了package.json,并将自定义功能移至node_modules文件夹。

向Firebase NodeJS添加自定义类的正确方法是什么?

修改

当我按照Doug Stevenson的建议并从我的package.json删除自定义类,并将该类移动到与index.js相同的目录时,我仍然会收到错误:< / p>

i  deploying functions
i  functions: ensuring necessary APIs are enabled...
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...

Error: Error parsing triggers: Cannot find module 'notificationFunctions'

Try running "npm install" in your functions directory before deploying.

修改2

确定。我想我必须改变将类导入require('./notificationFunctions')的方式,这样就可以在部署项目时删除所有错误。

然而,当我在云上运行代码时,我收到此错误:FIREBASE WARNING: Exception was thrown by user callback. TypeError: notificationFunctions.getNotificationPayload is not a function

我从代码中调用函数的方式是:const payload = notificationFunctions.getNotificationPayload(userLanguage, senderName, groupName, messageContent, messageType);

1 个答案:

答案 0 :(得分:2)

如果在函数文件夹中向项目添加代码,则无需对package.json依赖项进行任何更改。只有发布到NPM registry的模块才需要npm依赖项。

你的构建正在做什么是在NPM上寻找一个名为“notificationFunctions”的节点模块,那里显然不存在。您应该直接将模块代码与require()和{{1}}下的所有其他代码一起放在那里。

另外,请记住,node_modules未随代码一起部署。 Cloud Functions将获取服务器端的所有npm依赖项,并使它们可用于您的代码。