# Compiling Sass using gulp.js

Aug 2014

How are you compiling your Sass? If you’re not automating it using something like a Javascript Task-Runner, you’re probably wasting a lot of time.

### Using Sass

I’ve found Sass the preprocessor to be a brilliant tool for more organised and streamlined web development. Make sure you make use one of Sass’s best features – being able to define variables – and set useful variables to save repeating yourself.

This also allows you to edit all values assigned with the variable at once which saves copious amounts of time. I would advise you to create a separate variables .scss document to store these variables though. This can then be called on by placing @import “variables”; at the top of the main.scss file.

### Integrating Gulp.js

There are plenty of tools such as Yeoman which help you get started with your Grunt/Gulp tasks by providing lots of frequently used tasks when building webapps. If you’re simply building a static website, it will be probably be worth writing your own tasks to save unnecessary lines of code.

First of all you must install the gulp-sass package via npm running the following command in the terminal: (Ensure that you are in the desired directory)

\$ npm install gulp-sass --save-dev


Great.

Now let’s start by adding a task to compile our .scss and add it into our gulpfile.js.

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

//Sass
gulp.src('scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('css/'));
});


This here includes a basic task to compile any .scss file when ‘gulp sass’ is run and place it in the ‘/css’ folder.

That’s all good and well, and we can run gulp sass now in the right directory to run the ‘sass’ function we have defined, but this would be a burden having to keep running this everytime we made changes to our .scss files. This is where watch tasks come in. We will create a watch task to watch for any changes to the .scss files and automatically compile them for us. We also need to add it to our default task so it begins to watch the files when we run the gulp command through the terminal. This results in a final gulp.js file: (Note the changes under the // Watch tasks section and also the changes to our ‘default’ task at the end)

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

//Sass
gulp.src('scss/**/*.scss')
.pipe(sass())
.pipe(gulp.dest('css/'));
});


Now, when we run the command gulp in the current directory where we have been working, the default task will compile anything outstanding by running the sass function initially, and then it will run the watch task, so changes can be made and the Sass is complied automatically upon saving. As you can see below, you can make as many changes as you want to your Sass and it will continue to update the .css file until you stop the application running.
Voila! With a few lines of Javascript, you’ve built a way to automate the compilation of your .scss files.