Export multiple files as a 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 more ugly / short:

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

He feels "hacker."

Is there a cleaner way to do this?

+7
source share
2 answers

it works like this:

stuff.js

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

or if the object distribution operator is supported :

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

OtherFiles.js

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

stuff.one();
stuff.two();
+8
source
import * as stuff from "Path";  
import {foo,bar} from "Path";

you can do the same in export:

export function foo(){};
export function bar(){};
-2
source

Source: https://habr.com/ru/post/1682628/


All Articles