Configure your Gulp file for converting, concatenating and minifying your SASS files into CSS

Even though Gulp is a bit outdated task runner in web development, I am an old user of it, trust it and use it for the CSS generation in my blog. In this article we are going to see how I convert the SASS code into CSS, sanitize it and minify it.

There are three tasks we want to achieve:

The dependencies

Firstly we import the necessary Gulp plugins: gulp, gulp-clean-css, gulp-concat, and gulp-sass. The gulp-sass requires the sass compiler. Remember to install them with npm install gulp gulp-clean-css gulp-concat gulp-sass.

The Gulp tasks

The first task, named sass, compiles the SASS files (.sass) located in the _sass directory and pipes the compiled CSS to the ./public/styles/ directory. Then all the CSS files in this directory are getting minified from cleanCSS() and concatenated into a file named styles-comp.min.css. Finally this file is copied into the ./public/ folder.

The second task, which is the default task, runs the first sass task and it also sets up a watcher to recompile SASS files whenever they change.

The workflow

  1. Place your SASS files in the _sass directory
  2. Run gulp in the terminal to execute the default task
  3. The compiled CSS will be saved in ./public/styles/
  4. A minified and concatenated version (styles-comp.min.css) will also be generated and saved in ./public/

The script

var gulp = require('gulp');
var cleanCSS = require('gulp-clean-css');
var concat = require('gulp-concat');
const sass = require('gulp-sass')(require('sass'));

gulp.task('sass', function() {
    gulp.src("./_sass/*.sass")
        .pipe(sass())
        .pipe(gulp.dest("./public/styles/"));
        
    gulp.src('./public/styles/*.css')
        .pipe(cleanCSS())
        .pipe(concat('styles-comp.min.css'))
        .pipe(gulp.dest("./public/"));
});

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

Feel free to customize the script further based on your project’s needs!

comments powered by Disqus