I wish to split a large configuration .js file into multiple smaller files yet still combine them into the same module. Is this common practice and what is the best approach so that the module would not need extending when new files are added.
An example such as but not needing to update math.js when a new file is added.
math - add.js - subtract.js - math.js
// add.js
module.exports = function(v1, v2) {
return v1 + v2;
}
// subtract.js
module.exports = function(v1, v2) {
return v1 - v2;
}
// math.js
var add = require('./add');
exports.add = add;
var subtract = require('./subtract');
exports.subtract = subtract;
// app.js
var math = require('./math');
console.log('add = ' + math.add(5,5));
console.log('subtract =' + math.subtract(5,5));
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.
A module can have one and only one default export.
You can use the spread operator ...
or if that doesnt work Object.assign
.
module.exports = {
...require('./some-library'),
};
Or:
Object.assign(module.exports, require('./some-library'));
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