【问题标题】:jQuery and Underscore not loading in RequireJSjQuery 和 Underscore 未在 RequireJS 中加载
【发布时间】:2013-01-08 16:38:23
【问题描述】:

我对 Backbone 还很陌生,今天才开始尝试学习 AMD。我从 RequireJS 的网站安装了 RequireJS-jQuery 库。所以这是我的脚本标签,里面有 Laravel 路径调用:

<script data-main="{{ path('js/main') }}" 
src="{{ path('js/libs/requirejs/require-jquery.js') }}"></script>

我正在尝试确保一切都正确加载,因此我正在尝试console.log 我的依赖项。 Backbone 返回一个对象就好了。下划线和 jQuery 没有。这是我的main.js 文件:

  require.config({
    baseUrl: '../js/',
    paths: {
        jquery: 'libs/jquery/jquery-1.8.3.min',
        underscore: 'libs/underscore/underscore-min',
        backbone: 'libs/backbone/backbone-min'
    }
});

if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
  define( 'jquery', [], function () { return jQuery; } );
}

//the "main" function to bootstrap your code
require(['jquery', 'underscore', 'backbone', 'app'],
    function () {  
        var App = require('app');
        //App.initialize();
        console.log($);
        console.log(_);
        console.log(Backbone);
});

我有几个问题,我是否需要 jQuery 的路径,因为它是 RequireJS-jQuery 库的一部分?二,这是什么关于匀场?我需要垫片来让它工作吗?我正在使用 RequireJS-jQuery 的 v 2.1.4。

我尝试关注this post,但无法正常工作。我正在使用 AMD 版本的 Backbone 和 Underscore。 Underscore 和 jQuery console.log 为什么不会呢?

【问题讨论】:

  • 当我说他们不会 console.log 我的意思是它返回 function()

标签: jquery backbone.js underscore.js require amd


【解决方案1】:

当通过 require.js 请求任何文件时,它必须符合标准 AMD 定义,以便 IIFE 定义参数。

例如,在 jQuery 库中,他们添加了一个导出定义:

if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
  define( "jquery", [], function () { return jQuery; } );
}

这允许您在 IIFE 中引用 $

Shimming 添加了一个导出定义(类似于上面的 jQuery),所以如果你愿意,你可以让 _、$ 和 Backbone 指向适当的引用......但就个人而言,我不依赖于参数,而是依赖全局评估,为 dependencies 设置必要的垫片,否则,对于我自己的所有模块(我确实将每个文件定义为 AMD 模块),我使用内联需要定义。

例如:

require(['jquery','underscore','backbone', 'my-module'],function(){
    var MyModule = require('my-module');
});

希望以上内容有意义。

~根据你上面的代码,试试:

require(['jquery', 'underscore', 'backbone', 'app'],
    function () {  
        var App = require('app');
        //App.initialize();
        console.log($);
        console.log(_);
        console.log(Backbone);
});

【讨论】:

  • 我试过了,但似乎没有用。 jQuery 仍然不是 console.logging。
  • 好吧,我的观点更重要的是,不要依赖匿名函数中的参数定义,而是使用内联定义,并假设模块已经加载。即摆脱function ($, _, Backbone, App),而是使用'App'的内联require定义分配App,即require('app')和$或jQuery应该存在,因为你需要它。
  • 你能编辑我的代码来告诉我你的意思吗,我似乎没有明白。
  • 我就是这么想的。我仍然没有得到 jQuery 或 Underscore。
  • 会不会有其他事情发生?
猜你喜欢
  • 2012-06-07
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多