从其他文件导入Firebase函数的导入函数-javascript [英] Firebase Function import function from other file - javascript

查看:32
本文介绍了从其他文件导入Firebase函数的导入函数-javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript构建Firebase函数.现在,我有很多相互调用功能,并且我计划将这些功能移到不同的文件中,以避免index.js变得非常混乱.

I am building firebase function with javascript. Now i have a lot of inter-call function and i plan to move those function into different file to avoid index.js become very messy.

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

So below is the current file structure:

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

我想知道:

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

1) How to export the function from internalFunctions.js and import it to index.js.

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

2) How to call internalFunctions.js function from index.js.

我的代码是用JavaScript编写的.

My code is written in JavaScript.

已编辑

internalFunction.js将具有多个功能.

internalFunction.js will have multiple functions.

推荐答案

首先在文件中设置函数:

First you set the function in your file:

internalFunctions.js:

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

或者,如果您不喜欢花括号,那么

Or if you dont like a lot messing with curly braces:

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 文件中将该文件作为模块导入:

Then in your index.js file import the file as a module:

const ifunctions = require('./internalFunctions');

然后您可以在触发器或HTTP处理程序中直接调用它:

And then you can call it directly within your triggers or HTTP handlers:

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

});

这篇关于从其他文件导入Firebase函数的导入函数-javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆