Search code examples
coffeescriptsassgulpslim-lang

Gulp compiling SLIM/SASS/CoffeeScript on fly


There is the following Gulp file with tasks:

// gulp
var gulp = require('gulp');

// plugins
var connect = require('gulp-connect');
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var minifyCSS = require('gulp-minify-css');
var clean = require('gulp-clean');
var slim = require('gulp-slim');
var coffee = require('gulp-coffee');
var sass = require('gulp-sass');

// tasks
gulp.task('lint', function() {
  gulp.src(['./app/**/*.js', '!./app/bower_components/**'])
    .pipe(jshint())
    .pipe(jshint.reporter('default'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('clean', function() {
    gulp.src('./dist/*')
      .pipe(clean({force: true}));
});

gulp.task('minify-css', function() {
  var opts = {comments:true,spare:true};
  gulp.src(['./app/**/*.scss', '!./app/bower_components/**'])
    .pipe(sass())
    .pipe(minifyCSS(opts))
    .pipe(gulp.dest('./dist/'))
});

gulp.task('minify-js', function() {
  gulp.src(['./app/**/*.coffee', '!./app/bower_components/**'])
    .pipe(coffee({bare: true}))
    .pipe(uglify({
      // inSourceMap:
      // outSourceMap: "app.js.map"
    }))
    .pipe(gulp.dest('./dist/'))
});

gulp.task('copy-bower-components', function () {
  gulp.src('./app/bower_components/**')
    .pipe(gulp.dest('dist/bower_components'));
});

gulp.task('copy-html-files', function () {
  gulp.src('./app/**/*.slim')
    .pipe(slim({ pretty: true }))
    .pipe(gulp.dest('dist/'));
});

gulp.task('connect', function () {
  connect.server({
    root: 'app/',
    port: 8888
  });
});

gulp.task('connectDist', function () {
  connect.server({
    root: 'dist/',
    port: 9999
  });
});


// default task
gulp.task('default',
  ['lint', 'connect']
);
// build task
gulp.task('build',
  ['lint', 'minify-css', 'minify-js', 'copy-html-files', 'copy-bower-components', 'connectDist']
);

I want to use SLIM/SASS/CoffeeScript in my front-end work. But I must do 'gulp clean build' after each changes in order to translate SLIM to HTML, SASS to CSS, Coffee to JS. I want to do any changes and just refresh a page in the browser. How can I do it? Thanks in advance!


Solution

  • You need to put watchers on your files:

    gulp.task('watch', ['build','connectDist'], function() {
        gulp.watch(['./app/**/*.coffee', '!./app/bower_components/**'], ['minify-js']);
        gulp.watch(['./app/**/*.scss', '!./app/bower_components/**'], ['minify-css']);
        gulp.watch('./app/**/*.slim', ['copy-html-files']);
    })
    

    If you start gulp watch, first the build and connectDist tasks are getting executing, preparing your build directory. Then three watchers look at your main input files, and call the related tasks should something have changed.

    Please note that I called the connectDist task and not the connect one, mainly because all your browser readable files are stored in dist.