Mrweiner
Mrweiner

Reputation: 521

Gulp watch all .scss files and compile to css as siblings?

I've got a site with a handful of modules that need their css files to exist separate from one-another, but I'd like to write the styles using scss as well as leverage gulp for autoprefixing. Is it possible to watch for changes in any scss files under a given directory tree and then write the css for the updated file as a sibling? The structure would essentially be something like this (although it could have directories nested to greater depths):

Gulpfile.js
module1
- styles1.scss
- styles1.css
- dir
-- styles2.scss
-- styles2.css
module2
- dir
-- subdir
--- styles3.scss
--- styles3.css

I've got the following Gulpfile setup elsewhere to handle my general scss compilation but I'm not sure how I might modify it to instead handle the above scenario.

// Requirements 
var postcss = require('gulp-postcss');
var gulp = require('gulp');
var sass = require('gulp-sass');
var sassGlob = require('gulp-sass-glob');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var sassOptions = {
  errLogToConsole: true,
  outputStyle: 'expanded'
};

gulp.task('scss', function () {
  return gulp
    .src('scss/style.scss')
    .pipe(sourcemaps.init())
    .pipe(sassGlob())
    .pipe(sass(sassOptions).on('error', sass.logError))
    .pipe(postcss([require('postcss-flexibility')]))
    .pipe(autoprefixer())
    .pipe(sourcemaps.write(''))
    .pipe(gulp.dest('css'))
    .resume();
});

// Create 'watch' task
gulp.task('watch', function () {
  return gulp
    // Watch the input folder for change,
    // and run `sass` task when something happens
    .watch('scss/**/*.scss', gulp.series('scss'))
    // When there is a change,
    // log a message in the console
    .on('change', function (event) {
      console.log('File ' + event + ' was updated' + ', running tasks...');
    })
  ;
});

Upvotes: 0

Views: 952

Answers (1)

TheDancingCode
TheDancingCode

Reputation: 942

In your scss task, change the gulp.src glob to '**/*.scss', and the gulp.dest glob to '.'.

In your watch task, change the glob to '**/*.scss' as well.

Upvotes: 1

Related Questions