javascript - 我应该在每个文件中都需要一个模块还是需要一次并将其作为参数传递?

标签 javascript node.js

假设我有 50 个模块,每个模块都需要 Underscore 库。像那样加载 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
(..)

有什么区别吗?

最佳答案

模块在第一次加载后被缓存,所以你可以在每个文件中都要求它。 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/

关于javascript - 我应该在每个文件中都需要一个模块还是需要一次并将其作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27949235/

相关文章:

javascript - 如何将 Ajax 响应作为可下载文件发送到 Web 浏览器客户端?

Javascript,我可以垂直拉伸(stretch)文本吗

javascript - 如何释放网页上的系统资源/CPU使用率?

node.js - 我应该在文件/模块之间共享 Redis 连接吗?

javascript - Express.js 静态 html 与 get

javascript - 如何在 Node JS 中 gzip 一个 jade 模板

javascript - 获取 Node 模块目录的路径

javascript - 如何在不验证电子邮件或电话的情况下确认 Cognito 用户池中的用户?

javascript - 定义不能删除的属性?

mysql - 历史更新mysql node js