2013-03-26 74 views
0

我不知道为什么我不能用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()只调用一个回调的作品?

+0

不能确定文档页面未能解释?它非常彻底。 – 2013-03-26 12:54:43

+0

@SimonSmith文档没有解释为什么我需要在我的函数范围内使用require()和回调函数。从外面我可以var dep = require('dep') – jviotti 2013-03-26 16:41:33

+0

@jviotti我知道这是一个迟到的回复,但正如@Simon Smith在他的回答中指出的那样,它不起作用的原因是因为它不是简单的像普通代码一样执行。 Requirejs实际上会解析你的函数以调用'require',因此它可以构建一个依赖树。为了做到这一点,它需要知道给定模块的所有依赖关系。它不能动态地做到这一点,因为它在实际获取任何内容之前需要知道每个依赖项。 – Davy8 2015-09-10 14:55:13

回答

1

我会在这里跟进我的意见。

你不能没有已经require传递给它一个定义回调传递一个数组作为第一个参数的任何地方除了使用require。即便如此也有局限性。

尝试别的做到这一点的任何地方将抛出一个错误:

require('jquery', function() {}); 

http://requirejs.org/docs/errors.html#requireargs

你能做到这一点的唯一的一次是在这里:

define(function(require) { 
    var $ = require('jquery'); 
}); 

这仅仅是一个更好的方式写作:

define(['jquery'], function($) { 

}); 

第一个版本被称为糖语法 - http://requirejs.org/docs/whyamd.html#sugar

The AMD loader will parse out the require('') calls by using Function.prototype.toString(), then internally convert the above define call

我基本上只是重复上的是什么RequireJS文档解释,但我希望这使得它更清晰一点。

我也包括在不同的上下文这里这个话题 - How to achieve lazy loading with RequireJS?

+0

是的,我知道。我认为我的问题写得不好,对不起。试着现在就尽力修复它。请看一下 – jviotti 2013-03-27 03:04:36