Loading mustache using requirejs

2019-04-04 15:54发布

问题:

I would like to load and use mustache by requirejs.

Maybe this question has already asked:
AMD Module Loading Error with Mustache using RequireJS

Anyway I am trying to figure out how can I fix my code:


main.js

require.config({
    paths: {
        jquery: 'libs/jquery/jquery',
        underscore: 'libs/underscore/underscore-min',
        backbone: 'libs/backbone/backbone-optamd3-min',
        mustache: "libs/mustache/mustache"
    }
});

require([
    'views/app'
    ], function(AppView){
        var app_view = new AppView;
 });

app.js

define([
    'jquery',
    'underscore', 
    'backbone',
    "mustache"
    ], function($, _, Backbone, Mustache) {
        console.log($, _, Backbone, Mustache); // <-- *** Mustache is null ***
        // ......
       }
);

As you can see in the comment on app.js file, Mustache is null...
Should I use another library of Mustache? Here what I am using Mustache

回答1:

You should just create in your mustache directory a new file mustache-wrap.js which looks like this:

 define(['libs/mustache/mustache'], function(Mustache){
    // Tell Require.js that this module returns a reference to Mustache
    return Mustache;
 });

and then your main will be:

  mustache: "libs/mustache/mustache-wrap"


回答2:

Looks like Mustache supports AMD modules as of July '12. So it should now work out of the box with a loader such as require.js.



回答3:

Not sure if RequireJS 2.1.0 was out at the time of posting this question (and the answers) but the preferred way of handling this now is using shim config element (more info on project's docs page).

Your main.js would become:

require.config({
    paths: {
        jquery: 'libs/jquery/jquery',
        underscore: 'libs/underscore/underscore-min',
        backbone: 'libs/backbone/backbone-optamd3-min',
        mustache: "libs/mustache/mustache"
    },
    shim: {
        'mustache': {
            exports: 'Mustache'
        }
    }
});
(...)

That's effectively the same as wrapper suggested @AntoJs, but without the boilerplate code.

...but then, since Mustache supports AMD there's no need to wrap/shim in the first place!



回答4:

You could probably also do in-line named define in the code that consumes mustache, or somewhere in "main.js" (saves the trouble of creating *-wrap file)

define('mustache', ['libs/mustache/mustache'], function(){
    // Tell Require.js that this module returns a reference to Mustache
    return Mustache; // from global
});
require(
    ['jquery','underscore','backbone','mustache']
    , function($, _, BB, Mustache){
        // use them
    }
)