Skip to content

Instantly share code, notes, and snippets.

@cgmartin
Last active August 29, 2015 13:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cgmartin/10328349 to your computer and use it in GitHub Desktop.
Save cgmartin/10328349 to your computer and use it in GitHub Desktop.
grunt-newer: Check for newer @import .less files
//
// grunt-newer:
// Check for newer @import .less files example
// See: https://github.com/tschaub/grunt-newer/issues/29
//
grunt.initConfig({
// ...
newer: {
options: {
override: function(taskName, targetName, filePath, time, include) {
if (taskName === 'less') {
// call include with `true` if there are newer imports
checkForNewerImports(filePath, time, include);
} else {
include(false);
}
}
}
}
// ...
});
var fs = require('fs');
var path = require('path');
function checkForNewerImports(lessFile, mTime, include) {
fs.readFile(lessFile, "utf8", function(err, data) {
var lessDir = path.dirname(lessFile),
regex = /@import "(.+?)(\.less)?";/g,
shouldInclude = false,
match;
while ((match = regex.exec(data)) !== null) {
// All of my less files are in the same directory,
// other paths may need to be traversed for different setups...
var importFile = lessDir + '/' + match[1] + '.less';
if (fs.existsSync(importFile)) {
var stat = fs.statSync(importFile);
if (stat.mtime > mTime) {
shouldInclude = true;
break;
}
}
}
include(shouldInclude);
});
}
@tschaub
Copy link

tschaub commented Apr 10, 2014

Nice. The function should be named checkForNewerImports to be consistent with the config. Or change the config to match.

@cgmartin
Copy link
Author

@tschaub thanks for catching that... had copied from two separate sources. Fixed and included some missing requires.

@samzeng
Copy link

samzeng commented May 29, 2014

is that a stylus version? And how to use it?

@xinghul
Copy link

xinghul commented Nov 26, 2014

I don't think this is a good solution, by checking the mTime, it results in compiling the script no matter what.

@yonidor
Copy link

yonidor commented Feb 3, 2015

Helped me a lot, thanks!

@migreva
Copy link

migreva commented Mar 31, 2015

Loved this, thanks. Looks like grunt-newer updated their API again for the override function:

https://github.com/tschaub/grunt-newer#optionsoverride

I forked and updated the gist here if you wanna take a look:

https://gist.github.com/migreva/2a926b95f25366da657c

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment