Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 746
guagay_wk Avatar asked Aug 31 '25 15:08

guagay_wk


1 Answers

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.

like image 55
Timur Ridjanovic Avatar answered Sep 02 '25 13:09

Timur Ridjanovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!