使用RequireJS从Webjars中使用JQuery

时间:2015-03-05 15:56:51

标签: jquery maven requirejs webjars

我正在尝试将JQuery包含在使用maven构建的网络应用中,使用RequireJS定义Javascript个模块。

我遵循了RequireJS文档here,其中说明了如何将JQueryRequireJS一起使用。我还有一个maven版本。

这就是我的所作所为:

我的main.js,由RequireJS

HTML的数据主要调用
define(function() {
// Configuration of RequireJS
    requirejs.config({
        // No module can start with require. This can potentially allow easier definition of some elements
        enforceDefine : true,

        map : {
            '*': { 
                'jquery': 'libs/jquery',
            },

            // To make jquery work with requireJS: see http://requirejs.org/docs/jquery.html
            // 'jquery' wants the real jQuery module
            // though. If this line was not here, there would
            // be an unresolvable cyclic dependency.
            'libs/jquery': { 'jquery': 'jquery' },
        },

        // The base URL is just the top-level directory where the files are stored
        baseUrl : './',

        // Kick-start the application by loading these files
        deps : [ 'MyMainPanel' ],
    });
});

我定义了一个“自定义”JQuery(在RequireJS文档中),位于/libs/jquery.js

define(['jquery'], function (jq) {
    return jq.noConflict( true );
});

maven pom.xml

...
<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>${jquery.version}</version>
</dependency>
...

在使用jquery的模块的instanciation中,我收到以下错误:

GET http://localhost:8080/jquery.js 404 (Not Found)
require.js:166 Uncaught Error: Script error for: jquery
http://requirejs.org/docs/errors.html#scripterror

使用JQuery的模块如下:

define(['ractive',
        'jquery',
        function(Ractive,
                $,
){
    var Panel  = Ractive.extend({
        el:"mainPanel",

        oninit: function(){
            $.ajax({url: "/myURL"}).done(function(types){
                // Work
            })
        }
    })

    return Panel
})

1 个答案:

答案 0 :(得分:0)

我找到的唯一解决方案(解决方法)是使用“强制定义”值:

requirejs.config({
    enforceDefine : false,

    map : {
        'libs/jquery' : {
            'jquery' : "webjars/jquery/${jquery.version}/jquery"
        },

        '*': { 
            'jquery' : 'libs/jquery', 
        },
    },

    baseUrl : './',

    deps : [ 'MyMainPanel' ],
});

我不知道它为什么会起作用,但它确实有效。我会坚持下去,直到找到更好的解决方案。