Firebase函数如何从其他文件中导入函数 - JavaScript

9
我将使用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将有多个函数。


已经在这里回答了:https://dev59.com/91cQ5IYBdhLWcg3wA_BA - AarónBC.
哪一个是合适的解决方案?因为被接受的答案的评论实际上回答了我的疑虑,我不想在index.js中再次导出internalFunctions.js函数。我只想从index.js中调用internalFunctions.js中的一个函数。 - Jerry
抱歉,我应该更明确一些,我添加了一个答案,你可以看到导入的方式与帖子中相同,只是需要以不同的方式使用它。 - AarónBC.
1个回答

18

首先在你的文件中设置函数:

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...

});

我有一个额外的问题,如何从internalFunctions中调用另一个函数?(在同一个文件中) - Jerry
使用 module.exports.HelloWorld(); 或者只用 exports.HelloWorld(); - AarónBC.
我的意思是,在HelloWorld()函数内,我想调用AnotherFunction()来处理一些东西,我该如何调用它? - Jerry
是的,在internalFunctions.js文件中的一个函数内,你可以使用module.exports.HelloWorld();来调用一个本地函数。 - AarónBC.
如果你不喜欢这种方式声明和导出函数,你可以使用另一种方式,就像答案链接中提供的那样:https://gist.github.com/kimmobrunfeldt/10848413 - AarónBC.
我们是否仍然能够从internalFunctions.js向这些函数传递输入? - Jonathan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接