14

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 ?

2 Answers 2

17

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Link does not work.
-1
import * as stuff from "Path";  
import {foo,bar} from "Path";

you can still do the same in export:

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

1 Comment

The OP is not using an ES6 transpiler.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.