我想通过requirejs加载和使用小胡子。
也许这个问题已经问过:
AMD Module Loading Error with Mustache using RequireJS
无论如何,我想知道如何修复我的代码:
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 ***
// ......
}
);
正如您在app.js
文件的评论中所看到的,Mustache is null
...
我应该使用另一个胡子库吗?
这就是我使用的Mustache
答案 0 :(得分:17)
截至2012年7月,看起来像Mustache supports AMD modules。所以现在应该使用诸如require.js之类的加载器开箱即用。
答案 1 :(得分:9)
你应该在你的胡子目录中创建一个新文件mustache-wrap.js,如下所示:
define(['libs/mustache/mustache'], function(Mustache){
// Tell Require.js that this module returns a reference to Mustache
return Mustache;
});
然后你的主要是:
mustache: "libs/mustache/mustache-wrap"
答案 2 :(得分:7)
在发布此问题(以及答案)时,不确定RequireJS
2.1.0是否已用完,但现在处理此问题的首选方法是使用shim
配置元素(更多信息{{ 3}})。
你的main.js会变成:
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'
}
}
});
(...)
有效地与包装器建议@AntoJs相同,但没有样板代码。
...但是,由于Mustache支持AMD,所以首先不需要包装/垫片!
答案 3 :(得分:1)
您可能也会在使用小胡子的代码中执行内联命名的define,或者在&#34; main.js&#34; (省去了创建* -wrap文件的麻烦)
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
}
)