Skip to content

Instantly share code, notes, and snippets.

@just-boris
Created January 21, 2016 10:15
Show Gist options
  • Save just-boris/ea02ff33b09d6ce3b492 to your computer and use it in GitHub Desktop.
Save just-boris/ea02ff33b09d6ce3b492 to your computer and use it in GitHub Desktop.
Handlebars loader for node.js
const fs = require('fs');
const path = require('path');
const Handlebars = require('handlebars/dist/cjs/handlebars');
// configuration the same as webpack handlebars-loader has
const config = {
helperDirs: [
path.resolve(__dirname, '../src/helpers'),
path.resolve(__dirname, '../src/blocks')
]
};
// if you are using `runtime` in your helpers, they should get the same Handlebars instance
require.cache[require.resolve('handlebars/runtime')] = {exports: Handlebars};
// load helpers
Handlebars.registerHelper('helperMissing', function() {
if(arguments.length === 1) {
return;
}
const options = Array.from(arguments).pop();
const helper = config.helperDirs.reduce(function(helper, dir) {
return helper || require(path.join(dir, options.name));
}, null);
return helper.apply(this, arguments);
});
// there is no `partialMissing` thing, so we need to patch this method
const resolvePartial = Handlebars.VM.resolvePartial;
function patchResolvePartial(filename) {
return function(partial, content, options) {
if(!partial) {
partial = require(path.resolve(path.dirname(filename), options.name) + '.hbs');
}
return resolvePartial.call(this, partial, content, options);
};
}
//install require hook
require.extensions['.hbs'] = function(module, filename) {
Handlebars.VM.resolvePartial = patchResolvePartial(filename);
const templateString = fs.readFileSync(filename, 'utf8');
module.exports = Handlebars.compile(templateString);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment