Skip to content

Instantly share code, notes, and snippets.

@dshster
Forked from zonak/grunt-coffee.js
Created November 21, 2012 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dshster/4126706 to your computer and use it in GitHub Desktop.
Save dshster/4126706 to your computer and use it in GitHub Desktop.
grunt task for compiling CoffeScript
/*
* 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