Skip to content

Instantly share code, notes, and snippets.

@tyler-johnson
Last active December 14, 2015 10:29
Show Gist options
  • Save tyler-johnson/5072805 to your computer and use it in GitHub Desktop.
Save tyler-johnson/5072805 to your computer and use it in GitHub Desktop.
Simple directory watch and handlebar template precompile.
// DEPENDENCIES
var path = require('path'),
fs = require('fs'),
watch = require('watch'),
Handlebars = require('handlebars'),
glob = require("glob"),
_ = require('underscore');
// MAIN VARS
var exts = [ ".hbs" ],
src = "views",
dest = "public/js/templates.js";
// PRECOMPILE
function do_precompile() {
var fstream = fs.createWriteStream(dest, { flags: 'w' });
fstream.write("(function() {\n\tvar template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};\n\tHandlebars.partials = Handlebars.templates;\n\n");
glob(src + "/**", function (err, files) {
if (err) throw err;
_.each(files, function(file) {
var ext = path.extname(file);
if (_.contains(exts, ext)) {
var id = file.replace(src + "/", "").replace(ext, ""),
template = fs.readFileSync(file).toString();
fstream.write("\ttemplates['" + id + "'] = template(" + Handlebars.precompile(template) + ");\n\n");
}
});
fstream.end("})();");
});
}
// WATCH
watch.watchTree(src, function(file) {
if (_.isString(file) && _.contains(exts, path.extname(file))) {
if (nconf.get("NODE_ENV") === "development") console.log("Handlebar file '"+file+"' changed.");
do_precompile();
}
});
// RUN
do_precompile();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment