module.exports that include all functions in a sin

2020-05-25 18:39发布

问题:

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

回答1:

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

function bar() {
   //bar
}

function foo() {
   //foo
}

module.exports = {
    foo: foo,
    bar: bar
};

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



回答2:

I have done something like the following:

var Exported = {
   someFunction: function() { },
   anotherFunction: function() { },
}

module.exports = Exported;

I require it in another file and I can access those functions

var Export = require('path/to/Exported');
Export.someFunction();

This is essentially just an object with functions in it, and then you export the object.



回答3:

It is worth noting that in ES6, you can now export functions like this:

export function foo(){}
export function bar(){}
function zemba(){}

Simply write export before the functions you want to export. More information here.



回答4:

If you use ES6 you can do something like that:

function bar() {
   //bar
}

function foo() {
   //foo
}

export default { bar, foo };



回答5:

A really old question but I just had to solve the same issue myself. the solution I used was to define a Class inside the module to contain all my functions and simply export an instance of the class.

classes.js looks like this:

class TestClass
{
   Function1() {
        return "Function1";
    } 
    Function2() {
        return "Function2";
    }
}

module.exports = new TestClass();

app.js looks like this:

const TestClass = require("./classes");
console.log( TestClass.Function1);

just keep adding more functions to the class and they will be exported :)