2

Is there a way to compile directory of templates and store in array object using Webpack?

Explanation: I am now using list of handlebars templates. I precompile the list of templates using handlebars compiler in gulp.

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/', ''));
        }
      }));

I would then access templates through appname.templates array. It was working fine.

Now, I am moving to Webpack. If I use the handlebars-loader , it allows me to require every template by name like

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

Is there a way to get all templates in one directory as an array like

var templates = require("./*.handlebars");
Salman Mohammad
  • 182
  • 1
  • 14
Kannan J
  • 508
  • 5
  • 12
  • Maybe https://www.npmjs.com/package/glob-loader is what you want? – bejado Feb 15 '17 at 05:54
  • @bejado - Tx of pointing to glob loader. Yes, it loads dir of files, but I would need to apply handlebars loader also. Is there a way to call both. Also I am not sure how to import in code. Let me know if you have any suggestions. – Kannan J Feb 15 '17 at 08:46

1 Answers1

2

I usually would go to the folder you have your templates and have an templates/index.js file such as:

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

Then you can do:

import * as templates from './templates'

And templates is an object that holds all your templates. You can also do templates.templateA to access them by name.

albertfdp
  • 425
  • 4
  • 11
  • Thanks albertfdp for the great solution. Works perfectly. In my project, I have not enabled Babel and so I have to write it as `export {default as templateA} from 'templateA.handlebars'`. Info on the syntax was from the link [link](http://stackoverflow.com/questions/35665759/es6-how-can-you-export-an-imported-module-in-a-single-line) – Kannan J Feb 16 '17 at 07:33