使用 Require.js 未定义车把

Handlebars is undefined using Require.js

我将 Handlebars 与 Require.js 一起使用,但由于某些原因,Handlebars 未定义。

我的配置:

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" 所以感谢他的帮助!

您需要使用:

require(["handlebars.runtime"], function(Handlebars){`

而不是

require(["handlebars"], function(Handlebars){`

而且 shim 仅用于不支持 AMD 的模块。在您的示例中垫片完全没用。所有这些库都支持 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); 
});

就这些了。