Node.js global require

最后都变了- 提交于 2019-12-05 03:14:39

The usual practice in nodejs development is to just require() a module in each module that you need it. The module itself is cached by nodejs so the same module is returned every time and it isn't actually loaded over and over. Doing it this way rather than creating globals generally makes code more modular and reusable since each module uniquely specifies (with require() statements) what it needs rather than having a bunch of modules that depend upon some pre-existing global configuration which creates a lot more dependencies, load order issues, etc...

It is possible to make a single module that does require() on a bunch of other modules and then combines the results into a new master module if that is relevant or useful so other modules only have to require the new master module.

It is not recommended to use globals in place of just using a require() statement. Remember that in nodejs programming, most require() statements are just run at server initialization time and they are cached so there's little reason to avoid the benefits and modularity that using require() instead of globals provides.


I wouldn't personally recommend this because it messes with modularity, but in your specific example, you could also pass the utils module to the a.js constructor:

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