Node.js Combine module/exports from multiple files

11,544

Solution 1

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'));

Solution 2

If your NodeJs allows the spread (...) operator (check it here), you can do:

    module.exports = {
        ...require('./src/add'),
        ...require('./src/subtract')
    }

Solution 3

You can do this

// math.js 
module.exports = function (func){
    return require('./'+func);
}

//use it like this 
// app.js

var math = require('./math');
console.log('add = ' + math('add')(5,5));
console.log('subtract =' + math('subtract')(5,5));

Solution 4

You could create a subfolder to assign functions and other objects automaticly.

mymodule.js

const pluginDir = __dirname + '/plugins/';
const fs = require('fs');

module.exports = {};

fs.readdirSync(pluginDir).forEach(file => {
    Object.assign(module.exports,require(pluginDir + file));
});

plugins/mymodule.myfunction.js

module.exports = {

    myfunction: function() {
        console.log("It works!");
    }

};

index.js

const mymodule = require('mymodule.js');

mymodule.myfunction();
// It works!
Share:
11,544

Related videos on Youtube

rjinski
Author by

rjinski

Updated on October 09, 2022

Comments

  • rjinski
    rjinski over 1 year

    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));
    
  • Chad
    Chad about 6 years
    ... and if it doesn't?
  • kedoska
    kedoska about 6 years
    @chad, an option is probably to write javascript ES6 and use babel (or others) to produce ES5 and run it with the old node.js.
  • Apolo
    Apolo almost 4 years
    Object.assign has always been the way to do this before spread operator. module.exports = Object.assign({}, require('./src/add'), require('./src/subtract'));