Created
December 5, 2012 19:33
-
-
Save there4/4218777 to your computer and use it in GitHub Desktop.
GruntJS task for minify, handlebars, and JST compilation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*global process: true, module: true*/ | |
// JST-HB | |
// | |
// Description: Compile handlebars templates to JST file. | |
// | |
var fs = require('fs'), | |
path = require('path'), | |
Handlebars = require('handlebars'), | |
_ = require('underscore'), | |
minify = require('html-minifier'); | |
module.exports = function(grunt) { | |
grunt.task.registerMultiTask("jsthb", | |
"Compile handlebars templates to JST file", function() { | |
var | |
name = this.target, | |
data = this.data, | |
src = path.resolve(this.data.src), | |
dest = path.resolve(this.data.dest), | |
dir = path.resolve('./'), | |
namespace = this.data.namespace || null, | |
files = grunt.file.expand(src); | |
// let the developer know where we are writing | |
grunt.verbose.or.write('Writing to "' + dest + '"\n'); | |
// Write the destination file with the contents from the jsthb | |
// helper output. | |
grunt.file.write( | |
dest, | |
grunt.task.helper( | |
"jsthb", files, namespace, dir | |
) | |
); | |
// If we've had an error, the build needs to stop | |
if (this.errorCount) { return false; } | |
// Let the process continue, and let the developer know that | |
// everything went ok. | |
grunt.verbose.or.ok(); | |
}); | |
// Build a compiled template file | |
grunt.task.registerHelper("jsthb", function(files, namespace, dir) { | |
var source, contents; | |
// This file should be an anon function that inserts the JST | |
// or other namespace into the window namespace. | |
contents = "define(['use!handlebars'], function(Handlebars) { JST = {};\n"; | |
// Compile the template and place it into our compiled template object | |
contents += files ? _.map(files, function(filepath) { | |
var tpl, | |
path = filepath | |
.replace(dir + '/app/templates/', '') | |
.replace('.html',''); | |
tpl = minify.minify(grunt.file.read(filepath), { | |
removeComments: true, | |
collapseWhitespace: true | |
}); | |
return "JST['" + path + "'] " + | |
"= Handlebars.template(" + | |
Handlebars.precompile(tpl) + | |
");\n"; | |
}).join("\n") : ""; | |
return contents + "\n" + "return JST; });"; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment