Search code examples
csssassgulpgulp-watch

Gulp compile SASS into relative subfolder


If I have a file inside of components/root/sass/index.scss, how do I compile it to components/root/styles/index.css? Simply put, I want to replace sass in the path with styles, i.e. if I had a file at components/second/sass/file.scss, it would compile to components/second/styles/file.css.

This is my current code in gulpfile.js:

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function() {
  return gulp.src('components/**/sass/*.scss', {base: "./"})
    .pipe(sass())
    .pipe(gulp.dest('../styles/'));
})

gulp.task('default', function () {
  gulp.watch('components/**/sass/*.scss', ['sass']);
});

Solution

  • Rename each path replacing the "/sass" bit and it's extension via "gulp-rename" module.

    I would recommend having the path globbing in a variable, the watch as a independent task, and the default task with both the "sass" and "watch" tasks.

    var gulp = require('gulp');
    var sass = require('gulp-sass');
    var rename = require("gulp-rename");
    
    var componentsGlob = './components/**/sass/*.scss';
    
    gulp.task('sass', function() {
      return gulp.src(componentsGlob)
        .pipe(sass())
        .pipe(rename (function(path) {
          path.dirname = path.dirname.replace('/sass', '/styles');
          path.extname = ".css";
        }))
        .pipe(gulp.dest('./components/'));
    });
    
    gulp.task('watch', function () {
      gulp.watch(componentsGlob, ['sass']);
    });
    
    gulp.task('default', ['sass', 'watch']);