如何使用 RequireJS 加载 Handlebars 运行时



我是RequireJS的新手,并尝试使用RequireJS加载车把预编译模板。 它加载车把模板和运行时,但未定义车把运行时。

文件夹结构

www
 |__index.html
 |__js
    |__main.js
    |__lib
    |    |__jquery-1.10.1.min.js
    |    |__handlebars.runtime-v1.1.2.js
    |    |__require.js
    |__modules
    |    |__content.js
    |__templates
         |__content-tmpl.js     //handlebars precompiled template

索引.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="js/lib/require.js" data-main="js/main"></script>
</head>
<body>
<div class="header"></div>
<div class="content"></div>
</body>
</html>

主.js

requirejs.config({
    paths:{
        jquery:'lib/jquery-1.10.1.min',
        'handlebars.runtime':'lib/handlebars.runtime-v1.1.2'
    }
});
requirejs(['modules/content','jquery'],function (content,$) {
    $(function(){
        content.initModule();
    });
});

内容.js

define(['jquery','../templates/content-tmpl'],function($,template){
    return{
        initModule:function(){
            $('body').append(template());
        }
    }
});

内容-tmpl.js (编译的车把模板)

define(['handlebars.runtime'], function (Handlebars) {
//Error raise here. Handlebars is undefined.
    Handlebars = Handlebars["default"];
    var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
    return templates['content'] = template(function (Handlebars, depth0, helpers, partials, data) {
        this.compilerInfo = [4, '>= 1.0.0'];
        helpers = this.merge(helpers, Handlebars.helpers);
        data = data || {};
        return "<div>rn    Hello Handlebars and RequireJSrn</div>";
    });
});

控制台错误

TypeError: Cannot read property 'default' of undefined

我的猜测是handlebars.runtime.js不是AMD模块,因此您需要使用填充码配置它。在您的要求中.js配置添加

requirejs.config({
  shim: {
    "handlebars.runtime": {
      exports: "Handlebars"
    }
  }
});

这样,当你调用require("handlebars.runtime") 时,require.js就会知道抢窗。Handlebar 变量,并在脚本加载后将其传递给您。

如果您使用的是 RequireJS,则应包含运行时的 AMD 版本,在这种情况下不需要导出。

require.config({
    paths: {
        'handlebars.runtime': '//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.runtime.amd.min'
    }
});

然后,当您要访问 Handlebars 对象时(例如注册帮助程序)。

require(['handlebars.runtime'], function(HandlebarsRuntime) {
    var Handlebars = HandlebarsRuntime.default;
});

您可以在 https://github.com/ryan-blunden/handlebars-requrejs 查看使用编译的 Handlebars 模板和 RequireJS 的最新应用程序示例

最新更新