Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export multiple files as single module in node js

Here is a simple example of what I'm trying to achieve:

foo.js :

module.exports.one = function(params) { */ stuff */ }

bar.js :

module.exports.two = function(params) { */ stuff */ }

stuff.js:

const foo = require('Path/foo');
const bar = require('Path/bar');

I want to do :

otherFile.js:

stuff = require('Path/stuff');

stuff.one(params);
stuff.two(params);

I do not want to do [in stuff.js]

module.exports = {
one : foo.one,
two: bar.two
}

The solution I came with is :

const files = ['path/foo', 'path/bar']

module.exports =   files
    .map(f => require(f))
    .map(f => Object.keys(f).map(e => ({ [e]: f[e] })))
    .reduce((a, b) => a.concat(b), [])
    .reduce((a, b) => Object.assign(a, b), {})

or uglier/shorter :

module.exports = files
  .map(f => require(f))
  .reduce((a, b) => Object.assign(a, ...Object.keys(b).map(e => ({ [e]: b[e] }))));

It feels "hackish".

Is there a cleaner way to do this ?

like image 693
Sequoya Avatar asked Jul 31 '17 01:07

Sequoya


People also ask

How do I export multiple node js files?

Exporting Multiple Methods and Values We can export multiple methods and values in the same way: const getName = () => { return 'Jim'; }; const getLocation = () => { return 'Munich'; }; const dateOfBirth = '12.01. 1982'; exports.

Can you have multiple module exports in one file?

You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax. After the export keyword, you can use let , const , and var declarations, as well as function or class declarations.

Can we have 2 module exports?

You can export as many functions as needed as long as you remember that there can be only one default export. The default export in JavaScript is used to export a single/fallback value from a module. With a default export, you do not need to specify a name for the exported function. The filename is used by default.

Can you export with module exports?

By module. exports, we can export functions, objects, and their references from one file and can use them in other files by importing them by require() method.


1 Answers

it works this way:

stuff.js

module.exports = Object.assign(
    {},
    require('./foo'),
    require('./bar'),
);

or if Object Spread Operator is supported:

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

OtherFiles.js

var stuff = require('./stuff');

stuff.one();
stuff.two();
like image 145
Val Avatar answered Sep 20 '22 14:09

Val