假设我有 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/