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
I want to know:
1) How to export the function from internalFunctions.js and import it to index.js.
2) How to call internalFunctions.js function from index.js.
My code is written in JavaScript.
Edited
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!');
}
There are also other styles you can use: https://gist.github.com/kimmobrunfeldt/10848413
Then in your index.js file import the file as a module:
const ifunctions = require('./internalFunctions');
And then you can call it directly within your triggers or HTTP handlers:
ifunctions.HelloWorld();
Example:
//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...
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With