在多个文件中需要相同的模块 [英] Requiring same module in multiple files
问题描述
我在我的项目中使用了Underscore.js。几乎所有文件都有这行代码: var _ = require('underscore')
。
require
函数是同步的,因此每次使用时都会加载相同的文件。这是正确的做法吗?这不会影响性能吗?
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?
而不是这个,可以在 app.js $ c $中定义一个全局变量c>文件?
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.
推荐答案
来自node.js文档:
From the node.js documentation:
模块在第一次出现后被缓存已加载。这意味着
(除其他外)每次调用require('foo')将获得
完全相同的返回对象,如果它将解析为相同的
文件。
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. 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.
因此,要求下划线
的多次调用不会影响性能,因为它将加载模块的缓存版本。
来源: https://nodejs.org/api/modules.html
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
这篇关于在多个文件中需要相同的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!