Im trying to use gulp and jscs to prevent code smell. I also want to use watch so that this happens when ever a change is made. The problem I'm running into is jscs is modify the source file that is being watched. This causes gulp to go into an infinite loop of jscs modifying the file and then watch seeing the change and firing off jscs again and again and again ...
const gulp = require('gulp');
gulp.task('lint', function() {
return gulp.src('/src/**/*.js')
.pipe(jscs({
fix: true
}))
.pipe(jscs.reporter())
.pipe(gulp.dest('/src'));
});
gulp.task('watch', function() {
gulp.watch('/src/**/*.js', ['lint']);
});
It's generally a bad idea to override source files from a gulp task. Any Editors/IDEs where those files are open might or might not handle that gracefully. It's generally better to write the files into a separate
distfolder.That being said here's two possible solutions:
Solution 1
You need to stop the
gulp-jscsplugin from running a second time and writing the files again, thus preventing the infinite loop you're running into. To achieve this all you have to do is addgulp-cachedto yourlinttask:The first
cache()makes sure that only files on disk that have changed since the last invocation oflintare passed through. The secondcache()makes sure that only files that have actually been fixed byjscs()are written to disk in the first place.The downside of this solution is that the
linttask is still being executed twice. This isn't a big deal since during the second run the files aren't actually being linted.gulp-cacheprevents that from happening. But if you absolutely want to make sure thatlintis run only once there's another way.Solution 2
First you should use the
gulp-watchplugin instead of the built-ingulp.watch()(that's because it uses the superiorchokidarlibrary instead ofgaze).Then you can write yourself a simple
pausableWatch()function and use that in yourwatchtask:In the above the
watcheris stopped before thelinttask starts. Any.jsfiles written during thelinttask will therefore not trigger thewatcher. After thelinttask has finished, thewatcheris started up again.The downside of this solution is that if you save a
.jsfile while thelinttask is being executed that change will not be picked up by thewatcher(since it has been stopped). You have to save the.jsfile after thelinttask has finished (when thewatcherhas been started again).