-
-
Save dshster/4126706 to your computer and use it in GitHub Desktop.
grunt task for compiling CoffeScript
This file contains 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
/* | |
* Grunt Task File | |
* --------------- | |
* | |
* Task: coffee | |
* Description: Compile CoffeeScript files | |
* Dependencies: coffee-script | |
* | |
*/ | |
module.exports = function(grunt) { | |
var log = grunt.log, | |
file = grunt.file, | |
_ = grunt.utils._, | |
path = require('path'), | |
fs = require('fs'); | |
grunt.registerMultiTask('coffee', 'Compile CoffeeScript files', function() { | |
var files = file.match(this.file.src, file.watchFiles.changed), | |
dest = this.file.dest, | |
base = this.file.src.match(/^[^\*]*/)[0], | |
tmpFilePath; | |
// Delete any compiled files matching a pontentially deleted source coffee files | |
if (file.watchFiles.deleted) { | |
file.match(this.file.src, file.watchFiles.deleted).forEach(function(filepath) { | |
var tmpFilePath = path.join(dest, (filepath.replace(/\.coffee$/, '.js')).substr(base.length)); | |
if(path.existsSync(tmpFilePath)) { | |
fs.unlinkSync(tmpFilePath); | |
log.ok('File "' + tmpFilePath + '" deleted.'); | |
} | |
}); | |
}; | |
// If the task is called directly and not through a watch task | |
if (file.watchFiles.changed === null && file.watchFiles.deleted === null) { | |
log.writeln('Compiling all matching coffee files'); | |
files = file.expand(this.file.src); | |
} | |
// Compile all the files and save them at the defined destination | |
files.forEach(function(filepath) { | |
var js, | |
tmpFilePath = path.join(dest, (filepath.replace(/\.coffee$/, '.js')).substr(base.length)); | |
if(!path.existsSync(path.dirname(tmpFilePath))) { | |
file.mkdir(path.dirname(tmpFilePath)); | |
} | |
js = grunt.helper('coffee', filepath); | |
if(js.length) { | |
file.write(tmpFilePath, js); | |
log.ok('File "' + filepath + '" compiled to "' + tmpFilePath + '".'); | |
} | |
}); | |
// Fail task if errors were logged. | |
if (grunt.errors) { return false; } | |
}); | |
grunt.registerHelper('coffee', function(filepath) { | |
var coffee = require('coffee-script'), | |
js = ''; | |
try { | |
js = coffee.compile(grunt.file.read(filepath), { bare: true }); | |
} catch(e) { | |
log.error(e); | |
} | |
return js; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment