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
dist
folder.That being said here's two possible solutions:
Solution 1
You need to stop the
gulp-jscs
plugin 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-cached
to yourlint
task:The first
cache()
makes sure that only files on disk that have changed since the last invocation oflint
are 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
lint
task is still being executed twice. This isn't a big deal since during the second run the files aren't actually being linted.gulp-cache
prevents that from happening. But if you absolutely want to make sure thatlint
is run only once there's another way.Solution 2
First you should use the
gulp-watch
plugin instead of the built-ingulp.watch()
(that's because it uses the superiorchokidar
library instead ofgaze
).Then you can write yourself a simple
pausableWatch()
function and use that in yourwatch
task:In the above the
watcher
is stopped before thelint
task starts. Any.js
files written during thelint
task will therefore not trigger thewatcher
. After thelint
task has finished, thewatcher
is started up again.The downside of this solution is that if you save a
.js
file while thelint
task is being executed that change will not be picked up by thewatcher
(since it has been stopped). You have to save the.js
file after thelint
task has finished (when thewatcher
has been started again).