我不知道为什么我不能用require()
函数是这样的:RequireJS的自定义使用require()函数
// I'm using define's sugar syntax
define(function(require) {
// This works fine. It assigns myModule to the myModule variable (no callback needed)
var myModule = require('myModule');
var getModule = function(name) {
// This doesn work. Using require() here expects a callback
return require(name);
};
return getModule;
});
这第二require()
调用抛出(但考虑看看与DevTools显示, <name>
实际上加载):
Uncaught Error: Module name <name> has not been loaded yet for context: _
为什么第一require()
调用仅返回模块(不需要做一个回调的方式),但第二require()
只调用一个回调的作品?
不能确定文档页面未能解释?它非常彻底。 – 2013-03-26 12:54:43
@SimonSmith文档没有解释为什么我需要在我的函数范围内使用require()和回调函数。从外面我可以var dep = require('dep') – jviotti 2013-03-26 16:41:33
@jviotti我知道这是一个迟到的回复,但正如@Simon Smith在他的回答中指出的那样,它不起作用的原因是因为它不是简单的像普通代码一样执行。 Requirejs实际上会解析你的函数以调用'require',因此它可以构建一个依赖树。为了做到这一点,它需要知道给定模块的所有依赖关系。它不能动态地做到这一点,因为它在实际获取任何内容之前需要知道每个依赖项。 – Davy8 2015-09-10 14:55:13