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 ?
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With