在单个文件中需要js和多个已编译的Handlebar.js模板

RequireJS and multiple compiled Handlebar.js templates in a single file

本文关键字:js 编译 模板 Handlebar 文件 单个      更新时间:2024-05-17

我是RequireJS的新手。我在Java/Maven应用程序中同时使用RequireJSHandlebars.js

我还使用jknack的handlebas-maven插件来编译我的handlebars模板。模板需要进行编译,才能作为跨域解决方案的一部分工作。

插件正在编译我的模板并将它们合并到一个文件中。生成的文件(我们称之为template.js)包含如下内容:

define('a.template', ['handlebars'], function(Handlebars) {
  ...
  var templates = Handlebars.templates = Handlebars.templates || {};
  templates['a.template'] = template;
  var partials = Handlebars.partials = Handlebars.partials || {};
  partials['a.template'] = template;
  return template;
}
define('b.template', ['handlebars'], function(Handlebars) {
  ...
  var templates = Handlebars.templates = Handlebars.templates || {};
  templates['b.template'] = template;
  var partials = Handlebars.partials = Handlebars.partials || {};
  partials['b.template'] = template;
  return template;
}

经过一点阅读,我相信这些都是命名模板(我知道这不是最佳实践),但插件会这样生成它们,我宁愿不手动编辑生成的文件来删除名称,以防将来模板更改,我的团队中的其他人不得不重新生成它们。

现在,我想从单个文件加载我编译的Handlebar模板,并将它们与RequireJS一起使用。经过一番折腾,我终于找到了一个似乎有效的东西:

require.config({
  paths: {
    'handlebars': '//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min',
    'template': 'template'
  },
  shim: {
    'handlebars': {
      exports: 'handlebars'
    },
    'template': {
      exports: ['a.template','b.template']
    },
    'a.template': ['template'],
    'b.template': ['template'],
  }
});
define(['a.template', 'b.template'],
    function (aTemplate, bTemplate) {
... 

然而,当我加载页面时,我看到一个错误:

未捕获类型错误:未定义不是函数

我已经追踪到RequireJS中的"getGlobal"函数(我认为这是尝试的拆分)。因此,"template"的exports属性是数组而不是字符串,这似乎是一个问题。

这些模板似乎如我所期望的那样工作。


我不确定我所做的是否是错误的,还有更好的方法从一个文件加载多个编译的模板吗?

我是否发现了RequireJS或jknack的maven插件中的错误?

我在没有JavaScript错误的情况下完成了以下操作。

require.config({
  paths: {
    'handlebars': '//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min',
    'a.template': 'template',
    'b.template': 'template'
  },
  shim: {
    'handlebars': {
      exports: 'handlebars'
    }
  }
});
define(['a.template', 'b.template'],
    function (aTemplate, bTemplate) {
...