简体   繁体   English

在Node.js中导出模块时的依赖关系范围

[英]Scope of dependencies when exporting a module in Node.js

When exporting a module that has another dependency, is it best to include that dependency within the module export function or outside of it? 导出具有其他依赖关系的模块时,最好是在模块导出函数中还是在模块导出函数之外包含该依赖关系? I usually see the latter, but it seems like it would be best to keep it in the local scope. 我通常会看到后者,但似乎最好将它保留在本地范围内。

For example: 例如:

var foo = require('foo');

module.exports = function(d) {
    return foo(d)/2;
}

vs.

module.exports = function(d) {
    var foo = require('foo');

    return foo(d)/2;
}

Only things exposed on module.exports and global can be accessed from other modules in node. 只有在module.exportsglobalmodule.exports才能从节点中的其他模块访问。 Unlike in the browser, var creates a local reference. 与浏览器不同, var创建本地引用。 To quote from node's documentation : 引用节点的文档

In browsers, the top-level scope is the global scope. 在浏览器中,顶级范围是全局范围。 That means that in browsers if you're in the global scope var something will define a global variable. 这意味着在浏览器中,如果您在全局范围内,var会定义一个全局变量。 In Node this is different. 在Node中,这是不同的。 The top-level scope is not the global scope; 顶级范围不是全球范围; var something inside a Node module will be local to that module . Node模块内的var something 将是该模块的本地内容

The difference between the two versions is therefore minimal - the first incurs a lookup in the local scope, while the other hits require.cache every time the function is invoked. 因此,两个版本之间的差异是最小的 - 第一个版本在本地范围内进行查找,而其他require.cache每次调用函数时都需要require.cache From what I have seen of node code, the former ( var someVar = require('something'); ) seems to be preferred. 从我所看到的节点代码,前者( var someVar = require('something'); )似乎是首选。

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

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