question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

unable to split Firebase functions in multiple files

See original GitHub issue

I’m working with firebase functions and arrived to hundreds of functions, and now it is very hard to manage it in single index.js file as shown in their lots of examples

I tried to split that functions in multiple files like:

    --firebase.json
    --functions
      --node_modules
      --index.js
      --package.json
      --app
        --groupFunctions.js
        --authFunctions.js
        --storageFunctions.js

in this structure i devide my functions in three categories and put in that three files groupFunctions.js authFunctions.js storageFunctions.js and tried to import that files in index.js but i don’t know why it is not working for me

Here is groupFunctions.js

var functions = require('firebase-functions');
module.exports = function(){
    exports.onGroupCreate = functions.database.ref('/groups/{groupId}')
        .onWrite(event => {
            console.log(`A group is created in database named:${event.params.groupId}.`);
            // some logic...
            //...
        })
}

Here is index.js file:

var functions = require('firebase-functions');
module.exports = require("./app/groupFunctions")();

my editor not giving any warning in this code but when i deploy this code with firebase deploy --only functions it does not deploy function (if some functions already exist on firebase console, it remove all functions on deploy)

So I need help regarding this problem, looking forward to listen from you guise.

question is also asked on stackoverflow

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:7
  • Comments:35 (7 by maintainers)

github_iconTop GitHub Comments

37reactions
nicolasgarniercommented, Oct 19, 2020

Now you could even automate this a bit and register functions based on their file name. For instance with an index.js like this:

**UPDATE, this works:**

const fs = require('fs');
const path = require('path');

// Folder where all your individual Cloud Functions files are located.
const FUNCTIONS_FOLDER = './my_functs';

fs.readdirSync(path.resolve(__dirname, FUNCTIONS_FOLDER)).forEach(file => { // list files in the folder.
  if(file.endsWith('.js')) {
    const fileBaseName = file.slice(0, -3); // Remove the '.js' extension
    if (!process.env.FUNCTION_TARGET || process.env.FUNCTION_TARGET === fileBaseName) {
      exports[fileBaseName] = require(`${FUNCTIONS_FOLDER}/${fileBaseName}`);
    }
  }
});

Where your file structure is like:

    --firebase.json
    --functions
      --node_modules
      --index.js
      --package.json
      --my_functs
        --sendFollowerNotification.js
        --blurOffensiveImages.js
        --renderTemplate.js

EDIT: Edited to reflect new name of environment variable.

34reactions
oodavidcommented, Oct 19, 2020

I’ve created a slightly modified version of index.js that uses globbing to search for files ending with .function.js. This allows me to organise my directory in any manner.

/** EXPORT ALL FUNCTIONS
 *
 *   Loads all `.function.js` files
 *   Exports a cloud function matching the file name
 * 
 *   Based on this thread:
 *     https://github.com/firebase/functions-samples/issues/170
 */
const glob = require("glob");
const files = glob.sync('./**/*.function.js', { cwd: __dirname });
for(let f=0,fl=files.length; f<fl; f++){
  const file = files[f];
  const functionName = file.split('/').pop().slice(0, -12); // Strip off '.function.js'
  if (!process.env.FUNCTION_TARGET || process.env.FUNCTION_TARGET === functionName) {
    exports[functionName] = require(file);
  }
}

EDIT: Edited to reflect new name of environment variable.

Read more comments on GitHub >

github_iconTop Results From Across the Web

unable to split Firebase functions in multiple files
My editor not giving any warning in this code. But when I deploy this code with firebase deploy --only functions , it does...
Read more >
How to Split Firebase Cloud Functions for Better Code ...
In Firebase Cloud Function, you cannot initializeApp() more than once. What if you want to read a doc from Firestore which is in...
Read more >
Organize multiple functions | Cloud Functions for Firebase
Let's examine a case where you have two different repositories that deploy functions to the same Firebase project:
Read more >
Splitting index.ts, & exporting multiple Cloud Functions ...
In this episode of #AskFirebase, Firebase Engineers Jen Person, and Abe Haskins answer even more questions from Firebase developers just ...
Read more >
Write Cloud Functions - Google Cloud
The main file can also define multiple function entry points that can be ... Where possible, we recommend splitting up large multi-function codebases...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found