Search code examples
javascriptnode.jsimportheader

module.exports that include all functions in a single line


This is a follow-up question to In Node.js, how do I "include" functions from my other files?

I would like to include an external js file that contains common functions for a node.js app.

From one of the answers in In Node.js, how do I "include" functions from my other files?, this can be done by

// tools.js
// ========
module.exports = {
  foo: function () {
    // whatever
  },
  bar: function () {
    // whatever
  }
};

var zemba = function () {
}

It is inconvenient to export each and every function. Is it possible to have a one-liner that exports all functions? Something that looks like this;

module.exports = 'all functions';

It is so much more convenient this way. It is also less buggy in case one forgets to export certain functions later.

If not a one-liner, are there simpler alternatives that make coding more convenient? I just want to include an external js file made up of common functions conveniently. Something like include <stdio.h> in C/C++.


Solution

  • You can write all your function declarations first and then export them in an object:

    function bar() {
       //bar
    }
    
    function foo() {
       //foo
    }
    
    module.exports = {
        foo, bar
    };
    

    There's no magical one-liner though, you need to explicitly export the functions you want to be public.