Last active
August 29, 2015 14:09
-
-
Save josimard/ea29904cb58cc4b13ba6 to your computer and use it in GitHub Desktop.
Grunt PNGQuant Task
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
/** ////////////////////////////////////////////////////////////////////////////////////////// | |
* | |
* PNG Quant Grunt Task | |
* | |
* To install on OSX: brew install PngQuant | |
* To install on Windows or other OS: http://pngquant.org/ | |
* | |
* https://gist.github.com/josimard/ea29904cb58cc4b13ba6/ | |
* | |
* */ | |
// Command line flags | |
var skipPngQuant = process.argv.indexOf("--nopng") > -1; | |
grunt.registerMultiTask('pngquant', 'PNGQUant custom task (using child processes)', function() | |
{ | |
var done = this.async(); | |
if(skipPngQuant) | |
{ | |
console.log("Skipping PNG optimization..."); | |
done(); | |
return; | |
} | |
// Default options | |
var options = this.options({ | |
}); | |
var pathWithPngs = []; | |
function addPngPath(pngPath) | |
{ | |
var path = pngPath.substring(0, pngPath.lastIndexOf("/")); | |
if(pathWithPngs.indexOf(path)>-1) return; | |
pathWithPngs.push(path); | |
} | |
// For each grunt file request | |
this.files.forEach(function (f) | |
{ | |
// For each file in globing pattern | |
f.src.forEach(function (item) | |
{ | |
//if(!grunt.file.isDir(item)) return; | |
if(item.indexOf(".png")>-1) addPngPath(item); | |
}); | |
}); | |
var async = grunt.util.async; | |
async.forEach(pathWithPngs, function(path, next) | |
{ | |
// http://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback | |
var exec = require('child_process').exec; | |
// http://nodejs.org/api/child_process.html | |
exec("cd "+path+"; pngquant *.png --ext .png --force", function (error, stdout, stderr) | |
{ | |
if (error !== null) { | |
if((error+"").indexOf("command not found")>-1) { | |
throw("\n\nPNGQuant NOT FOUND! \n * To install go to http://pngquant.org \n * Install on OSX with HomeBrew: brew install PngQuant\n\nTo skip PNG optimization: use 'grunt --nopng'\n"); | |
//done(); | |
} | |
console.log('pngquant error: ' + error); | |
} | |
console.log("Optimized PNGs in '"+path+"'"); | |
next(); | |
}); | |
}, function(error) { | |
done(!error); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment