Skip to content

Instantly share code, notes, and snippets.

@chrisirhc
Created January 21, 2014 05:53
Show Gist options
  • Save chrisirhc/8535016 to your computer and use it in GitHub Desktop.
Save chrisirhc/8535016 to your computer and use it in GitHub Desktop.
Watch sass files with awareness of the dependency graph (so that files that don't need to be recompiled don't get recompiled).
module.exports = function (grunt) {
var fs = require('fs');
grunt.registerTask('sasswatch', 'Watch Sass with awareness of dependency graph', function () {
var options = this.options({
sassPath: 'sass',
logFile: null,
style: 'nested',
loadPath: null,
cacheLocation: null,
src: null,
dest: null
});
var args = [
'--scss',
'--style', options.style,
'--cache-location', options.cacheLocation,
'--load-path', options.loadPath,
'--watch',
options.src + ':' + options.dest
];
// Add sourcemap option if Sass supports it (check --help for option)
grunt.util.spawn({
cmd: options.sassPath,
args: ['--help']
}, function (err, res) {
if (res.toString().indexOf('--sourcemap') !== -1) {
args.unshift('--sourcemap');
}
startDaemon(options, args);
});
return true;
});
function startDaemon(options, args) {
var sassDaemon = grunt.util.spawn({
cmd: options.sassPath,
args: args,
// Run from current working dir and inherit stdio from process
opts: {
cwd: process.cwd(),
stdio: options.logFile ? ['ignore', 'pipe', 'ignore'] : 'inherit'
}
}, function (err, res /*, code */) {
if (err) {
grunt.log.error(res);
} else {
grunt.log.writeln('Sass daemon died. I\'m not sure why.');
}
});
if (!sassDaemon) {
grunt.log.error('Could not start sass.');
return false;
} else if (options.logFile) {
sassDaemon.stdout.pipe( getLogStream(options.logFile) );
}
// Listen for terminate signal and clean up sassDaemon
process.on('SIGTERM', function () {
if (sassDaemon) {
sassDaemon.kill();
sassDaemon = null;
}
process.exit();
});
process.on('exit', function () {
if (sassDaemon) {
sassDaemon.kill();
}
});
}
function getLogStream(logFilePath) {
return fs.createWriteStream(logFilePath, {flags: 'a'});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment