[英]Loading mustache using requirejs
我想通过requirejs加载和使用小胡子。
也许这个问题已经问过:
使用RequireJS使用Mustache的AMD模块加载错误
无论如何,我想弄清楚如何修复我的代码:
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
...
我应该使用另一个胡子库吗? 这就是我使用的胡子
从2004年7月开始,看起来Mustache 支持AMD模块 。 所以现在应该使用诸如require.js之类的加载器开箱即用。
您应该在您的胡子目录中创建一个新文件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"
在发布此问题(以及答案)时不确定RequireJS
2.1.0是否已用完,但现在处理此问题的首选方法是使用shim
config元素( 项目文档页面上的更多信息)。
你的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,所以首先不需要包装/垫片!
您也可以在使用小胡子的代码中执行内联命名的define,或者在“main.js”中的某处执行(省去了创建* -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
}
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.