Requiring same module in multiple files

﹥>﹥吖頭↗ 提交于 2019-12-04 18:23:59

问题


I'm using Underscore.js in my project. Almost all files have this line of code: var _ = require('underscore'). The require function is synchronous so the same file is loaded each time it is used. Is this the right thing to do? Doesn't this affect performance?

Instead of this, is it okay to define a global variable in the app.js file?

_ = require('underscore')

I've read that you shouldn't use global variables, but this seems to be a valid use case.


回答1:


From the node.js documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

So multiple calls to requiring underscore will not affect the performance as it will be loading a cached version of the module.
Source: https://nodejs.org/api/modules.html



来源:https://stackoverflow.com/questions/30038680/requiring-same-module-in-multiple-files

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