0
votes

I'm trying to include JQuery in a web app built with maven, using RequireJS to define Javascript modules.

I followed RequireJS documentation here, which explains how to do to use JQuery with RequireJS. I have in addition a maven build.

Here's what I did:

My main.js, called by the data-main of RequireJS in my 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' ],
    });
});

I defined a "custom" JQuery (as in RequireJS documentation), lying in /libs/jquery.js

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

And in my maven pom.xml:

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

At the instanciation of a module using jquery, I get the following error:

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

The module using JQuery is the following one:

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

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

    return Panel
})
1
What web framework are you using and how are you exposing the WebJars via a URL?James Ward
I use Spring-boot and a few other webjars (RactiveJS for example). RactiveJS works fine with RequireJS, not JQueryRémi Doolaeghe
The result is : Uncaught TypeError: Cannot read property 'noConflict' of undefined in my custom requireJsRémi Doolaeghe
Not sure what to do about that one. Sorry.James Ward

1 Answers

0
votes

The only solution I found (which is a workaround) is playing woth "enforceDefine" value:

requirejs.config({
    enforceDefine : false,

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

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

    baseUrl : './',

    deps : [ 'MyMainPanel' ],
});

I don't know why it works, but it works. I'll keep it so until I find a better solution.