On-demand require()

青春壹個敷衍的年華 提交于 2019-12-20 03:46:41

问题


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?


回答1:


This may possible if you called the "MainClass" to dynamically load the additional modules on-demand. But I suspect this will also mean an adjustment in the api to access the module.

I am guess your motivation is to "avoid" the extra processing used by "non-required modules". But remember Node is single threaded so the memory footprint of loading a module is not per-connection, it's per-process. Loading a module is a one-off to get it into memory.

In other words the modules are only ever loaded when you start your server not every-time someone makes a request.

I think you looking at this from client-side programming where it's advantages to load scripts when they are required to save on both processing and or http requests.

On the server the most you will be saving is few extra bites in memory.




回答2:


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


来源:https://stackoverflow.com/questions/12138983/on-demand-require

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!