Gulp Changed doesn't work

2020-02-14 07:40发布

问题:

I have previously used gulp changed with my JS without a problem. However now I am trying to use gulp-changed and gulp-newer on my scss files without it detecting which file has changed.

var changed    = require('gulp-changed');
var newer = require('gulp-newer');
var SRC = './stylesheets/**/*.scss';
var DEST = './stylesheets';

gulp.task('sass', function () {   
    return gulp.src(SRC)
        .pipe(changed(DEST)) //tried newer here as well 
        .pipe(sass())
        .pipe(gulp.dest(DEST))
});

When changing a scss file it will output there has been a change but not change any scss

[BS] Watching files...
[09:26:13] Starting 'sass'...
[09:26:14] Finished 'sass' after 180 ms

Watch

gulp.task('watch', ['setWatch', 'browserSync'], function () {
    gulp.watch('./stylesheets/**/*.scss', ['sass']);
});

The output file expected exists and hasn't been changed since yesterday.

How can I get the scss to only compile changed files.

回答1:

This has been annoying me for the past few days as well, and I think I've found an alternate solution. I saw above that you got it working, but I figured I might as well share anyway in case it helps someone.

It requires gulp-cached (which I was already using, but I couldn't get gulp-changed or gulp-newer to work either). Initially I tried caching at the beginning of my compile pipeline like how changed|newer (are supposed to?) work, but that failed too. After a minute I realized my obvious mistake: cache operations need to happen after all processing and output files are ready to be written to the destination directory, but right before that actually happens.

Ergo:

gulp.watch('path/to/**/*.scss')
    .pipe(sass())
    <<... rename, minify, etc ...>>
    .pipe(cached('sass_compile'))
    .pipe(gulp.dest('path/to/dest/'));

That's it. The cache is empty when the Gulp process starts so all Sass files are compiled, their compiled versions (CSS) added to the cache, and then written to disk.

Then, when you edit and save a SCSS file, Sass will again recompile everything matching the src glob, but if the contents match (cache hit) then only whitespace or formatting was changed in the SCSS, and the call to gulp.dest doesn't happen. If the version in the cache differs (miss), the contents are written to disk.