我使用带有Require.js的Handlebars,但由于某些原因,Handlebars是一个unifined。
我的配置:
require.config({
paths: {
underscore: "lib/underscore-min", //1.8.3
backbone: "lib/backbone-min", //1.2.3
jquery: "lib/jquery-2.1.4.min", //2.1.4
marionette: "lib/backbone.marionette.min", //2.4.3
handlebars: "lib/handlebars.runtime.amd.min", //4.0.5
shim: {
"underscore": {
exports: "_"
},
"backbone": {
deps: ["underscore", "jquery"],
exports: "Backbone"
},
"jquery": {
exports: "jquery"
},
"marionette": {
deps: ["backbone", "jquery"],
exports: "Marionette"
},
"handlebars":{
exports: "Handlebars"
}
}
});
...而不是在同一个文件中:
require(["handlebars"], function(Handlebars){
"use strict";
console.log(Handlebars); //undefined
});
在另一个档案中:
define(["handlebars"], function(Handlebars){
"use strict";
console.log(Handlebars); //still undefined
});
我也使用预编译模板,这些模板工作得很好,所以我不知道,可能是什么问题。
提前致谢!
----解决方案----
正如Rajab指出的那样,问题在于我使用了"handlebars"
代替"handlebars.runtime"
,所以感谢他的帮助!
答案 0 :(得分:1)
您需要使用:
require([“handlebars.runtime”],function(Handlebars){`
而不是
require([“handlebars”],function(Handlebars){`
并且shim仅用于不支持AMD的模块。在你的例子中,Shim完全没用。所有这些库都支持AMD。例如,查看backbone.js中的16行:
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
handlebars.runtime.amd.js中的或行1002
define('handlebars.runtime', ['exports', 'module', './handlebars/base' ... etc
所有依赖项已在其中。所以你只需要配置路径:
require.config({
paths: {
underscore: "lib/underscore-min",
backbone: "lib/backbone-min",
jquery: "lib/jquery-2.1.4.min",
marionette: "lib/backbone.marionette.min",
handlebars: "lib/handlebars.runtime.amd.min",
}
}
require(['handlebars.runtime'], function(HandlebarsOrWhateverNameYouWantItStillWillbeHandlebars){
"use strict";
console.log(HandlebarsOrWhateverNameYouWantItStillWillbeHandlebars);
});
就是这样。