Kazuto
Kazuto

Reputation: 158

Watch recursive scss files in gulp

I'm using gulp for compiling several themes from a base theme. If I make changes to a subfile "watch" does not recognize the changes. It only recognize the changes if a file of those themes is changed.

My folder structure

├── node_modules
├── src/
│   ├── base/
│   │   ├── bootstrap
│   │   └── custom
│   ├── themes/
│   │   ├── theme1.scss
│   │   └── theme2.scss
│   └── main.scss
└── gulpfile.js

theme1.scss imports main.scss main.scss imports all bootstrap files and the _all.scss from custom dir.

My gulp config:

gulp.task('styles', function () {
    gulp.src('src/themes/*.scss')
        .pipe(sourcemaps.init())
        .pipe(sass().on('error', sass.logError))
        .pipe(autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe(cleanCSS())
        .pipe(rename({ suffix: '.min' }))
        .pipe(sourcemaps.write('/'))
        .pipe(gulp.dest('./css/themes'));
});

if I try to use src/**/*.scss as gulp.src it tries to compile every single file inside src/base/bootstrap and src/base/custom and crashes, because the variables can't be found.

What I want to achieve: Watcher sees changes in src/base/custom/_header.scss and compiles theme1.scss and theme2.scss

Can anyone help me setting my configuration accordingly?

Upvotes: 0

Views: 606

Answers (1)

lofihelsinki
lofihelsinki

Reputation: 2571

There doesn't seem to be a watcher-task. You need to have a different set of files to watch and a different set to compile.

Define a watcher-task with a globof files to watch:

Gulp 4

// Watch for file changes in any .scss file
gulp.task("watch-styles", function () {
    return gulp.watch(['src/**/*.scss'], gulp.series('styles'));
    //return gulp.watch(['src/base/custom/_header.scss'], gulp.series('styles'));
});

Gulp 3

// Watch for file changes in any .scss file
gulp.task("watch-styles", function() {
  var watcher = gulp.watch(['src/**/*.scss'], ['styles']);
  //var watcher = gulp.watch(['src/base/custom/_header.scss'], ['styles']);
});

Your compiling function stays the same. Here the src glob points to the files you want to compile:

gulp.task('styles', function () {
    gulp.src('src/themes/*.scss')
        .pipe(sourcemaps.init())
        .pipe(sass().on('error', sass.logError))
        .pipe(autoprefixer({
            browsers: ['last 2 versions'],
            cascade: false
        }))
        .pipe(cleanCSS())
        .pipe(rename({ suffix: '.min' }))
        .pipe(sourcemaps.write('/'))
        .pipe(gulp.dest('./css/themes'));
});

Upvotes: 1

Related Questions