javascript – 如何使用RequireJS加载Handlebars运行时

前端之家收集整理的这篇文章主要介绍了javascript – 如何使用RequireJS加载Handlebars运行时前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是RequireJS的新手,并尝试使用RequireJS加载手柄预编译模板.它加载了把手模板和运行时,但Handlebars运行时未定义.

文件夹结构

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

的index.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>

main.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();
    });
});

content.js

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

content-tmpl.js(Compiled Handlebars模板)

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>\r\n    Hello Handlebars and RequireJS\r\n</div>";
    });
});

控制台错误

TypeError: Cannot read property 'default' of undefined

解决方法

我的猜测是handlebars.runtime.js不是AMD模块,所以你需要使用shim config配置它.在你的require.js配置中添加
requirejs.config({
  shim: {
    "handlebars.runtime": {
      exports: "Handlebars"
    }
  }
});

这样,当你调用require(“handlebars.runtime”)时,require.js会知道抓取window.Handlebars变量并在加载脚本后将其传递给你.

猜你在找的JavaScript相关文章