【问题标题】:How can I use the Handlebars runtime with Require.js?如何将 Handlebars 运行时与 Require.js 一起使用?
【发布时间】:2014-03-04 22:13:05
【问题描述】:

在 Grunt 的 package.json 中,我指定了一个把手编译器:

"grunt-contrib-handlebars": "0.7.0"

在 Gruntfile 中,我正在预编译把手模板:

handlebars:
  compile:
    options:
      amd: true
      namespace: false
    files: [{
      expand: true
      cwd: 'src/mustache/',
      src: ['**/*.mustache']
      dest: 'public/js/compiled/templates'
      ext: '.js'
    }]

每个编译的模板都有一个需要把手的 AMD 包装器:

define(['handlebars'], function(Handlebars) {
return Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
...

在 Bower 的 bower.json 中,我指定了把手:

"handlebars": "1.3.0"

在我的 RequireJS 配置中,我指定了车把运行时:

require.config
  baseUrl: '/js/compiled/'
  paths:
    'jquery': '../bower_components/jquery/jquery'
    'underscore': '../bower_components/underscore/underscore'
    'backbone': '../bower_components/backbone/backbone'
    'handlebars': '../bower_components/handlebars/handlebars.runtime.amd'
  ...

(此处来源https://github.com/components/handlebars.js/blob/v1.3.0/handlebars.runtime.amd.js

当编译的模板需要把手时

Handlebars = require 'handlebars'

车把未定义!我在这里做错了什么!?如有任何帮助,我将不胜感激!

我宁愿不使用任何 require 插件。

【问题讨论】:

    标签: javascript requirejs gruntjs handlebars.js bower


    【解决方案1】:

    您的示例中已编译的 AMD 模板不是 Handlebars 1.3.0 模板编译器将输出的内容。这可能是 grunt-contrib-handlebars 使用 1.3.0 之前的版本来编译模板的问题。

    此外,在使用 Handlebars AMD 运行时不需要做任何特别的事情。例如,您的最小值(用于 Handlebars 运行时 AMD 加载程序)应如下所示。不需要 deps、shims 或 export。

    requirejs.config({
      ...
      paths: {
      'handlebars.runtime': 'lib/handlebars.runtime.amd'
      }
    });
    

    那么如果你想访问 Handlebars 对象(也许是为了注册助手),那么你需要从返回的对象中访问默认属性。

    var Handlebars = require('handlebars.runtime').default;
    

    您可能还想查看我在 GitHub 上的代码库 https://github.com/ryan-blunden/handlebars-requrejs,它显示了 Handlebars 和 RequireJS 一起工作。

    【讨论】:

      【解决方案2】:

      将其声明为handlebars.runtime.amd.js 将需要查找handlebars.runtime.amd.js.js,因此第一个问题可能与此有关。

      当使用带有 Require 的 Handlebars 时,我遇到了 runtime.amd 版本的问题,而是发现使用 handlebars.js 进行配置并声明 jQuery dep 是成功的:

      require.config
        baseUrl: '/js/compiled/'
        paths:
          'jquery': '../bower_components/jquery/jquery'
          'underscore': '../bower_components/underscore/underscore'
          'backbone': '../bower_components/backbone/backbone'
          'handlebars': '../bower_components/handlebars/handlebars'
        shim:
          handlebars: 
            deps: ['jquery']
            exports: 'Handlebars'
      

      【讨论】:

      • 不幸的是,这不适用于优化的构建。它仅适用于未优化的构建,因为 Handlebars 对象已添加到全局范围。
      • 啊!很抱歉无意中知道我以后会遇到麻烦。会留下答案,以防其他人出现。
      • 我遇到了类似的问题,发现在构建配置中使用wrapShim: true 可以让我在优化构建中使用Handlebars。有关详细信息,请参阅this question
      猜你喜欢
      • 1970-01-01
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      相关资源
      最近更新 更多