简体   繁体   English

在多个文件中需要相同的模块

[英]Requiring same module in multiple files

I'm using Underscore.js in my project.我在我的项目中使用 Underscore.js。 Almost all files have this line of code: var _ = require('underscore') .几乎所有文件都有这行代码: var _ = require('underscore') The require function is synchronous so the same file is loaded each time it is used. require函数是同步的,因此每次使用时都会加载相同的文件。 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?而不是这个,在app.js文件中定义一个全局变量可以吗?

_ = require('underscore')

I've read that you shouldn't use global variables, but this seems to be a valid use case.我读过您不应该使用全局变量,但这似乎是一个有效的用例。

From the node.js documentation:从 node.js 文档:

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.这意味着(除其他外)每次调用 require('foo') 都会返回完全相同的对象,如果它解析为相同的文件。

Multiple calls to require('foo') may not cause the module code to be executed multiple times.多次调用 require('foo') 可能不会导致模块代码被多次执行。 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.因此多次调用 required underscore不会影响性能,因为它将加载模块的缓存版本。
Source : https://nodejs.org/api/modules.html来源https : //nodejs.org/api/modules.html

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

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