Search code examples
javascriptrequirejshandlebars.js

Handlebars is undefined using Require.js


I'm using Handlebars with Require.js, but for some reasons, Handlebars is undifined.

My config:

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"
        }
    }
});

...and than in the same file:

require(["handlebars"], function(Handlebars){
    "use strict";
    console.log(Handlebars); //undefined
});

In an other file:

define(["handlebars"], function(Handlebars){
    "use strict";

    console.log(Handlebars); //still undefined
});

I'm also using precompiled templates, which are working perfectly fine, so I have no idea, what could be the problem.

Thanks in advance!

---- SOLUTION ----

As Rajab pointed out, the problem was that I used "handlebars" instead of "handlebars.runtime" so thanks for his help!


Solution

  • You need to use:

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

    instead of

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

    and also shim is used only for modules that don't support AMD. Shim completely useless in your example. All these libraries support AMD. For example look at 16 line in backbone.js:

    define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
    

    or line 1002 in handlebars.runtime.amd.js

    define('handlebars.runtime', ['exports', 'module', './handlebars/base' ... etc
    

    All dependencies already inside it. So you need only paths in config:

    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); 
    });
    

    that's all.