node.jssassgulpgulp-sassgulp-newer

Use Gulp Newer on Array of Sources


I am trying to speed up my watch task by optimizing scss compilation task. Orginally I had all of my scss compiling into one big app.css file but I found that if I remove some @imports that are rarely changes(ie Foundation styles) that it would cut my compile time in half, so I moved all those imports into a seperate global.scss file.

My question is how can I modify my gulp file so that it only recompiles my global.scss file when a change has been detected to one of those @imports. And then if a change is detected to one of my @imports in app.scss it will only recompile that file?

I tried using gulp-newer like seen in this SO question: Only compile sass if a file has changed using gulp

But when I change a @import file from app.scss it is also recompiling my global.scss file

I've also tried gulp-cached and gulp-changed with no luck so far.

File Organization

/src/assets
  /scss
    /app.scss
    /global.scss
/dist/assets
  /css
    /app.css
    /global.css

Gulpfile:

function styles() {
  return gulp.src(['src/assets/scss/app.scss', 'src/assets/scss/global.scss'])
    .pipe(newer('dist/assets/css'))
    .pipe($.sourcemaps.init())
    .pipe(sass({ includePaths: PATHS.sass })
      .on('error', sass.logError))
    .pipe($.autoprefixer({
      overrideBrowserslist: COMPATIBILITY
    }))
    .pipe($.if(PRODUCTION, $.cleanCss({ compatibility: 'ie9' })))
    .pipe($.if(!PRODUCTION, $.sourcemaps.write()))
    .pipe(gulp.dest('dist/assets/css'))
    .pipe(browser.reload({ stream: true }));
}

Solution

  • I was able to find a solution using gulp incremental builds and gulp-dependents

    There's a good explanation here: NPM Gulp > retrieve SCSS import filepaths

    I had to modify my src() from looking at the parent scss files to looking at all the scss files. My styles task now completes in under 6s(compared to the 20s+ originally)

    Updated Function

    import dependents    from 'gulp-dependents';
    function styles() {
        return gulp.src('src/assets/scss/**/*.scss', { since: gulp.lastRun(styles) })
        .pipe(dependents())
        .pipe($.sourcemaps.init())
        .pipe(sass({ includePaths: PATHS.sass })
          .on('error', sass.logError))
        .pipe($.autoprefixer({
          overrideBrowserslist: COMPATIBILITY
        }))
    
        .pipe($.if(PRODUCTION, $.cleanCss({ compatibility: 'ie9' })))
        .pipe($.if(!PRODUCTION, $.sourcemaps.write()))
        .pipe(gulp.dest('dist/assets/css'))
        .pipe(browser.reload({ stream: true }));
    }