如何将车把运行时与 Require.js 一起使用



在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'

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

我宁愿不使用任何需要的插件。

示例中编译的 AMD 模板不是 Handlebars 1.3.0 模板编译器将输出的内容。这可能是使用低于 1.3.0 的早期版本编译模板的 grunt-contrib-handlebars 的问题。

此外,使用车把 AMD 运行时时不需要做任何特殊操作。例如,您的最小值(对于车把运行时AMD加载程序)应如下所示。不需要 deps、s垫片或导出。

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 协同工作。

将其

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

当将 Handlebars 与 require 一起使用时,我在使用 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'

最新更新