Search code examples
node.jsrequireondemand

On-demand require()


Say I create a library in ./libname which contains one main file: main.js and multiple optional library files which are occasionally used with the main object: a.js and b.js.

I create index.js file with the following:

exports.MainClass = require('main.js').MainClass; // shortcut
exports.a = require('a');
exports.b = require('b');

And now I can use the library as follows:

var lib = require('./libname');
lib.MainClass;
lib.a.Something; // Here I need the optional utility object
lib.b.SomeOtherThing;

However, that means, I load 'a.js' and 'b.js' always and not when I really need them.

Sure I can manually load the optional modules with require('./libname/a.js'), but then I lose the pretty lib.a dot-notation :)

Is there a way to implement on-demand loading with some kind of index file? Maybe, some package.json magic can play here well?


Solution

  • Looks like the only way is to use getters. In short, like this:

    exports = {
        MainClass : require('main.js').MainClass,
        get a(){ return require('./a.js'); },
        get b(){ return require('./a.js'); }
    }