Adding RequireJS module that uses jquery on a page

2019-07-04 03:49发布

问题:

I have an add-on to an application (call it appX) that allows users to create their own customizations using javascript, css and appX's webservices api.

Usually customizations are small and do not involve a lot of external libraries/plugins but when they do have external libs the typical users' library of choice is jQuery.

In the next version of appX they are using jQuery natively which I know is going to break some of the customizations.

So I have a need to modularize this situation. I have some other problems that are coming up and RequireJS seems like a good solution to these issues. I just need to figure out how to apply RequireJS properly for this situation

In my POC I'm loading require.js as follows:

<!--A bunch of other script including jQuery (but not require) are loaded already -->
<script type="text/javascript" src="/custom/js/require.js"></script>
<script type="text/javascript" src="/custom/js/dostuff.js"></script>

We'll call the jQuery loaded with appX jqueryx and the one I want to load jqueryp (p for private)

jQuery utilizes AMD and by default uses this definition internally:

define( "jquery", [], function () { return jQuery; } ); 

But in this case RequireJS is loaded AFTER jQuery (jqueryx) so there will be no default 'jquery' definition correct?

Some more background before I show you my problem... the file structure is like this:

appx
    /js:
        jqueryx.js
        other.js
appx
    /custom/js:
        jqueryp.js
        dostuff.js

Looking at the RequireJS api it seems that I should be doing something like this:

require.config({
    baseUrl : 'custom/js',
    paths : { 'jquery' : 'jqueryp'},
    map: {
      '*': { 'jquery': 'jquery-private' },
      'jquery-private': { 'jquery': 'jquery' }
   }
});

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

require(['jquery'], function(jq){
    console.log(jq.fn.jquery);
});

But when I do this I get an error:

Mismatched anonymous define() module: function (jq)...

I've played around with switching references to jquery, jquery-private as it's kind of confusing but with no progress.

How should I be applying RequireJS to this situation?

回答1:

Almost a year late but better than no answer at all...

The following part should be moved into a "jquery-private.js" file:

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

You can't define a module in your main entry point. Even if you could, the module has no name so how would you reference it?