我应该在每个文件中需要一个模块还是需要一次并将其作为parameter passing?
比方说,我有50个模块,每个需要Underscore库。 加载下划线50次更好吗?
//a module var _ = require('underscore');
或者最好从主文件传递它:
//app.js var _ = require('underscore'); require('./app_modules/module1.js')(_); // passing _ as argument require('./app_modules/module2.js')(_); // passing _ as argument require('./app_modules/module3.js')(_); // passing _ as argument (..)
它有什么区别?
模块在第一次被加载后被caching,所以你可以在每个文件中要求它就好了。 require()
调用Module._load
:
Module._load = function(request, parent, isMain) { // 1. Check Module._cache for the cached module. // 2. Create a new Module instance if cache is empty. // 3. Save it to the cache. // 4. Call module.load() with your the given filename. // This will call module.compile() after reading the file contents. // 5. If there was an error loading/parsing the file, // delete the bad module from the cache // 6. return module.exports };
请参阅: http : //fredkschott.com/post/2014/06/require-and-the-module-system/
第一个选项通常是最好的。
由于需求被caching,所以select第二个选项没有提高性能。 使用第一个选项的优点是更容易理解,并且不需要使每个模块都以Underscore库作为参数的行为。
但是,您可能希望能够轻松更改正在使用的库。 如果是这样的话,第二种select是有道理的,因为你只需要改变主文件中的库。 无论如何,我相信这是用例并不普遍,所以可能你使用第一个选项是很好的。
- Grunt:跨多个dirs项目缩小js,使每个dir的内容变成一个缩小的文件
- 节点摩卡柴asynchronous – 一切都传递,即使它应该失败
- 在nodejs express模块中处理所有事件之前发送响应
- JavaScript代码的解释 – 在三元IF运算符前面的Tilde符号
- 为什么on('data')监听器将两个不同的请求解释为一个请求,除非您添加超时
- node.js JSON.parse reviver不报告重复键?
- 如何创build一个引用其他咕噜任务的咕task任务
- 对大多数请求使用socket.io是不是很好,或者我应该只用它来将数据推送到客户端?
- 如何在Html的下拉菜单中访问匹配的数据?