说我在./libname中创建一个库,其中包含一个主文件:main.js和多个可选库文件,这些文件有时与主对象a.js和b.js一起使用.
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.
我创建具有以下内容的index.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;但是,这意味着我总是加载"a.js"和"b.js",而不是在我真正需要它们时加载.
However, that means, I load 'a.js' and 'b.js' always and not when I really need them.
当然可以用require('./libname/a.js')手动加载可选模块,但是随后我丢失了漂亮的lib.a点符号:)
Sure I can manually load the optional modules with require('./libname/a.js'), but then I lose the pretty lib.a dot-notation :)
是否可以通过某种索引文件实现按需加载?也许某些package.json魔术可以在这里很好地发挥作用?
Is there a way to implement on-demand loading with some kind of index file? Maybe, some package.json magic can play here well?
推荐答案看起来唯一的方法是使用吸气剂.简而言之,像这样:
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'); } }更多推荐
按需require()
发布评论