我正在用javascript构建firebase函数。现在我有很多调用函数,并且我计划将这些函数移到不同的文件中,以避免index.js变得非常困惑。

因此,下面是当前文件结构:

/functions
   |--index.js
   |--internalFunctions.js
   |--package.json
   |--package-lock.json
   |--.eslintrc.json

我想知道:

1)如何从internalFunctions.js导出函数并将其导入到index.js。

2)如何从index.js调用internalFunctions.js函数。

我的代码是用JavaScript编写的。

编辑

internalFunction.js将具有多个功能。

最佳答案

首先,在文件中设置功能:

internalFunctions.js:

module.exports = {
    HelloWorld: function test(event) {
        console.log('hello world!');
    }
};

或者,如果您不喜欢把花括号弄得一团糟,请执行以下操作:
module.exports.HelloWorld = function(event) {
    console.log('hello world!');
}

module.exports.AnotherFunction = function(event) {
    console.log('hello from another!');
}

您还可以使用其他样式:https://gist.github.com/kimmobrunfeldt/10848413

然后在 index.js 文件中,将该文件作为模块导入:
const ifunctions = require('./internalFunctions');

然后,您可以直接在触发器或HTTP处理程序中调用它:
ifunctions.HelloWorld();

示例:
//Code to load modules
//...
const ifunctions = require('./internalFunctions');

exports.myTrigger = functions.database.ref('/myNode/{id}')
    .onWrite((change, context) => {

      //Some of your code...

      ifunctions.HelloWorld();

      //A bit more of code...

});

10-05 20:48
查看更多