简体   繁体   English

按需require()

[英]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 . 假设我在./libname创建一个库,其中包含一个主文件: main.js和多个可选库文件,这些文件有时与主对象一起使用: a.jsb.js

I create index.js file with the following: 我使用以下命令创建index.js文件:

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. 但是,这意味着,我总是加载“ a.js”和“ b.js”,而不是在我真正需要它们时加载。

Sure I can manually load the optional modules with require('./libname/a.js') , but then I lose the pretty lib.a dot-notation :) 当然,我可以使用require('./libname/a.js')手动加载可选模块,但随后我丢失了漂亮的lib.a点符号:)

Is there a way to implement on-demand loading with some kind of index file? 有没有一种方法可以用某种索引文件实现按需加载? Maybe, some package.json magic can play here well? 也许,一些package.json魔术可以在这里正常播放?

This may possible if you called the "MainClass" to dynamically load the additional modules on-demand. 如果您调用“ MainClass”来按需动态加载其他模块,则可能会这样做。 But I suspect this will also mean an adjustment in the api to access the module. 但是我怀疑这也将意味着对api的调整以访问该模块。

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. 但是请记住,Node是单线程的,因此加载模块的内存占用不是每个连接而是每个进程。 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. 我认为您是从客户端编程看的,在需要保存处理和/或http请求的情况下,加载脚本的优点是它的优势。

On the server the most you will be saving is few extra bites in memory. 在服务器上,您最多可以节省的内存很少。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM