Browsed by
Tag: gulp.js

Setting up SASS Compiler using Gulp

Setting up SASS Compiler using Gulp

For future reference a basic SASS compiler using gulp.

Requirements:

  • NPM installed
  • Node.js installed
  • Gulp installed

Installing Gulp

$ [sudo] npm install gulp -g

The sudo command is optional but I needed it to install.

Setting up the compiler…

$ mkdir base-flat-html
$ cd base-flat-html/

$ npm init

$ mkdir sass
$ mkdir css
$ touch sass/theme.scss

This creates a directory,
changes to the new directory.
Initialises NPM in the directory which guides you through creating a package.json file.
Creates a folder called sass. This will contain all the SASS files.
Creates a folder called css. This will contain all the compiled CSS files.
Creates a file called theme.scss in the sass directory.

$ npm install gulp --save-dev

Install Gulp to the directory. This will update your package.json file.

$ npm install gulp-sass --save-dev
$ npm install gulp-cssnano --save-dev
$ npm install gulp-rename --save-dev
$ npm install gulp-wait --save-dev

These lines install:

  • Gulp SASS Compiler
  • Gulp CSS minifier
  • Gulp file renamer
  • Gulp wait module – I use to give the files time to save otherwise it can get stuck in an endless loop when we run gulp watch.

Create a new file called gulpfile.js this will contain all the tasks we want gulp to run.

$ touch gulpfile.js

First add gulp and all the required gulp modules we installed.

var gulp = require('gulp');
var sass = require('gulp-sass');
var cssnano = require('gulp-cssnano');
var rename = require('gulp-rename');
var wait = require('gulp-wait');

Then setup a task for compiling the SASS files

gulp.task('sass', function() {
	return gulp.src('sass/theme.scss')
		.pipe(wait(1500))
		.pipe(sass())
		.pipe(gulp.dest('css'))
});

This task takes the SASS file theme.scss and then waits 1500ms before running the compiler and then saving it to the css folder.

Next I create a task for minifying the compiled CSS.

gulp.task('minicss', function() {
	return gulp.src('css/theme.css')
		.pipe(cssnano())
		.pipe(rename({
			suffix: '.min'
		}))
		.pipe(gulp.dest('css'))
});

This takes the compiled theme.css file and minifies it. Then it creates a renamed copy with .min in the filename and saves it to the css directory.

Finally I add a watch task so that these two tasks will run whenever a change is made to the SASS files.

gulp.task('watch', function() {
	gulp.watch('sass/**/*.scss', gulp.series('sass','minicss', function(done) {
		done();
	}));
}); 

This watches the sass folder and runs the two tasks in sequence whenever a sass file is changed.

Full Code is here : https://github.com/dgrumbler/base-flat-html

To install run:

$ npm init
$ npm install