【问题标题】:How to load array of handlebar templates through web pack?如何通过 web pack 加载一系列车把模板?
【发布时间】:2017-07-03 15:44:35
【问题描述】:

有没有办法编译模板目录并使用Webpack存储在数组对象中?

说明:我现在正在使用车把模板列表。我在gulp 中使用handlebars compiler 预编译模板列表。

gulp.src('client/src/templates/**/*.hbs')
  .pipe(gulp_handlebars({
      handlebars: handlebars,
       compilerOptions:{
        knownHelpers: helpers,
        knownHelpersOnly:true}
      }))
      .pipe(wrap('Handlebars.template(<%= contents %>)'))
      .pipe(declare({
        namespace: 'appname.templates',
        noRedeclare: true, 
        processName: function(filePath) {
          return declare.processNameByPath(filePath.replace('client/src/templates/', ''));
        }
      }));

然后我将通过appname.templates 数组访问模板。它工作正常。

现在,我正在转向 Webpack。如果我使用 handlebars-loader , 它允许我按名称要求每个模板,例如

var template = require("./file.handlebars");

有没有办法将一个目录中的所有模板作为数组获取,例如

var templates = require("./*.handlebars");

【问题讨论】:

  • 也许npmjs.com/package/glob-loader是你想要的?
  • @bejado - 指向 glob 加载器的 Tx。是的,它加载文件的目录,但我还需要应用把手加载器。有没有办法同时调用。另外我不确定如何在代码中导入。如果您有任何建议,请告诉我。

标签: javascript webpack handlebars.js


【解决方案1】:

我通常会转到您有模板的文件夹并有一个templates/index.js 文件,例如:

export templateA from './templateA.handlebars'
export templateB from './templateB.handlebars'
export templateC from './templateC.handlebars'
...

那么你可以这样做:

import * as templates from './templates'

templates 是一个包含所有模板的对象。您也可以通过templates.templateA 按名称访问它们。

【讨论】:

  • 感谢 albertfdp 的出色解决方案。完美运行。在我的项目中,我没有启用 Babel,所以我必须将其写为export {default as templateA} from 'templateA.handlebars'。语法信息来自链接link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 1970-01-01
相关资源
最近更新 更多