Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Combine module/exports from multiple files

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));
like image 458
rjinski Avatar asked May 09 '14 11:05

rjinski


People also ask

Can you 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.

How many exports can a module have?

A module can have one and only one default export.


1 Answers

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'));
like image 130
Kevin Upton Avatar answered Sep 20 '22 05:09

Kevin Upton