按需require()

编程入门 行业动态 更新时间:2024-10-28 07:26:41
本文介绍了按需require()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

说我在./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()

本文发布于:2023-11-25 03:47:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628193.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:按需   require

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!