Donkey Shame Donkey Shame - 4 months ago 21
Sass (Sass) Question

gulp-autoprefixer and gulp-sass creating infinite sass compilation loop with default gulp task

I'm getting an infinite sass compilation loop with the following (simplified) gulp file.

'use strict';

// include gulp and all plugins
var gulp = require('gulp'),
notify = require('gulp-notify'),
rename = require('gulp-rename'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
autoprefixer = require('gulp-autoprefixer');


var app = {
src: 'styles/main.scss',
watch: 'styles/**/*.*',
dest: 'styles/dist/'
};

// compile sass, apply autoprefixer
gulp.task('sass', function(){
console.log('compiling SASS files')
return gulp.src(app.src)
.pipe(drano())
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(gulp.dest(app.dest))
.pipe(sourcemaps.write(app.dest))
.pipe(rename('main.css'));
});

// create watch task
gulp.task('watch', function(){
gulp.watch(app.watch, ['sass']);
});

gulp.task('default', ['sass','watch']);


When I run
gulp sass
task by itself, it's fine. But when I run the default task (
gulp
), the sass recompiles endlessly.

I really need to get autoprefixer working. Any suggestions would be greatly appreciated!

Answer

You are watching your destination folder. The glob styles/**/*.* matches every file in styles/dist/ as well. So what happens is:

  • You modify styles/main.scss
  • styles/main.scss matches styles/**/*.* => execute sass task
  • sass task generates styles/dist/main.css
  • styles/dist/main.css matches styles/**/*.* => execute sass task
  • sass task generates styles/dist/main.css
  • styles/dist/main.css matches styles/**/*.* => execute sass task
  • etc...

You need to exclude styles/dist/ from your watch:

var app = {
  src: 'styles/main.scss',
  watch: ['styles/**/*.*', '!styles/dist/**/*'],
  dest: 'styles/dist/'
};

Another approach would be to limit your watch to only .scss files:

var app = {
  src: 'styles/main.scss',
  watch: 'styles/**/*.scss',
  dest: 'styles/dist/'
};

Whatever you do you have to make sure your watched files don't include the files in your destination directory.