All Articles Kinsa Creative

Compile Sass on Save with Gulp Watch

Expedite stylesheet development by automatically compiling Scss to CSS on save by using Gulp.

This can be further expedited by setting VSCode, if that's the editor, to autosave. In Settings, search for "auto save" and enable Files to Auto Save onFocusChange or afterDelay. For editing side-by-side with rendered output, afterDelay is probably the way to go. For editing full-screen, onFocusChange will save when switching from the editor window to the browser window.

Install the Gulp CLI globally:

npm install gulp-cli -g

Intall Sass, and Gulp-Sass:

npm install sass gulp-sass --save-dev

Create a gulpfile in the root of the project:

touch gulpfile.js

Add to that:

'use strict';

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

const compileSass = () => {
    // point to the Scss file
    return gulp.src('./path/to/scss/main.scss')
        // compress the CSS to reduce file size
        .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
        // point to the directory where CSS should be saved; the CSS file will have the same filename as the Sass file but with the .css file extension
        .pipe(gulp.dest('./path/to/css'));
}

exports.compileSass = compileSass;
exports.watch = () => {
        // listen for any changes to any scss files in the scss directory and its subdirectories and run the compileSass function when a change is heard
    gulp.watch('./path/to/scss/**/*.scss', compileSass);
};

Run it:

gulp watch

Edit the main.scss file and save it. The watch task should run automatically and the CSS file should be overwritten with changes.

Feedback?

Email us at enquiries@kinsa.cc.