RequireJS,jquery仍未定义

我知道这已经讨论过了,但是经过一段时间的搜索,我无法弄清楚为什么我的小设置没有正确地用requireJS加载jquery。

我正在从’file://’运行一个小样本html页面并尝试通过调用require来加载2个模块:

  • jQuery的
  • 我写的一个自定义模块

如果我的自定义模块正确加载(我可以在require调用中使用它的别名,jquery总是未定义)

我试图在require.config中设置路径,以及shim(导出’$’或’jQuery’),但它不起作用。

我可以让jquery正确加载的唯一方法是删除所有路径定义并命名我的文件系统’jquery.js’上的jquery文件

这是我的配置:

main.js:

require.config({ baseUrl: 'scripts', paths: { jquery: 'jquery-2.1.3.min' //does not work //jquery: 'http://code.jquery.com/jquery-2.1.3.min.js' //does not work either } }); console.log( "main.js is loaded" ); //this is correctly ouputed to the console 

的test.html:

          require( ['jquery','custom'], function($, Custom){ console.info('$:'); console.info($); //outputs undefined console.info('Custom:'); console.info(Custom); //outputs my custom object });    

再一次,如果我删除jquery的所有路径定义,并且只是将我的jquery js文件命名为’jquery.js’,它就会工作,但这很麻烦。

有人能指出我正确的方向吗?

问题是您通过data-main加载RequireJS配置,该配置位于data-maindata-main属性仅告诉RequireJS加载那里列出的模块,但加载仍然是异步的 ,因此main可能会 RequireJS尝试加载jQuery 之后加载。 发生这种情况时,RequireJS无法找到jQuery,并且$未定义。 (顺便提一下,我建议你在RequireJS配置enforceDefine设置为true ,这样你就会收到一条错误消息,告诉你模块什么时候没有加载。这比有一个未定义的符号更好。)

一种解决方案是将配置移到main之外。 所以你从main删除它并将它添加到一个加载RequireJS前面的script元素:

   

或者您可以嵌套require调用以强制main在任何其他模块之前加载:

 require(['main'], function () { require(['jquery','custom'], ... });