Fun With Gulp – compiling and minifying SASS

Okay, so it’s been a few weeks since I’ve posted anything “codey” on here – I’ve been busy with a few things which I may or may not talk about in the future but, suffice to say, it’s given me a bit of focus on a few different priorities. One of these is pushing myself to understand Node.js and how it can help my development workflow. I’ve already talked about my use of VS-Code as an IDE and some of the plugins I’ve been using there, but one of the things that’s bugged me for a while is how basic the Easy SASS compiler I was using is. It’s not great for working with partials, for example, and is a bit of a blunt tool all things considered. It’s great for people who don’t want to get their hands dirty, but… I’m not one of those people.

So, Node.js! It’s a tool that you can use to run Javascript server side and can automate various different parts of your development workflow, from spinning up servers to scaffolding sites and components – like all good tools it’s flexible enough to work around how you already do things and can help you improve and build on your toolbox even further. I’ve been using it for a couple of different things but one of those is helping me move away from that Easy SASS plugin and start to use Gulp to compile my SASS on a project-by-project basis. Here’s how I got started.

Credit where credit’s due, this article right here was instrumental in me understanding Gulp, how it works and how to best implement it – https://css-tricks.com/gulp-for-beginners/. By all means, go and read that – there are some bits in there that I won’t be covering here because I didn’t really put them into play, but it’s a really easy read and clearly lays out what you need to do and what all the components you’ll be using are. Still with me? Here’s my methodolgy. As always I’ll be coming at this as a Windows user, but a lot of this stuff is pretty much the same across the board.

Step 1: Install Node.js and NPM

Node.js allows Javascript to be run server side to “do things” in applications and NPM is Node Package Manager – a command line tool that lets you install and manage different components in Node. Gulp is one such component but before you can use that you should grab Node.js from the official website. Install that and meet me at step 2.

Step 2: Install Gulp

Right, with NPM installed, fire up your terminal of choice. I use Windows PowerShell rather than the standard Command Prompt. It’s nicer and does things in a more Linuxey way including using commands like ‘ls’. You can check NPM is installed properly if you want by running:

npm -v

All good? Right, now we need to install Gulp globally. Do that by running:

npm install gulp -g

Now we need to get Gulp running in our project.

Step 3: Create a simple project and install Gulp into it

Let’s make something really straightforward. Take this as a file structure:

- my-project
  - sass
    - style.scss
  - css
  - index.html

What we’re going to do is write our sass code into style.scss and have Gulp compile that, spitting out the result into css in a .css and .min.css format so that we can include it in index.html and make our page look pretty. With that set up, point your terminal at the root folder and instantiate NPM in there:

npm init

This will create all the relevant package files for going forwards. Once that’s done you can install Gulp as a package:

install gulp --save-dev

Using –save-dev here ensures Gulp is included as a dev dependency in the package.json file.

With all that out of the way, let’s start compiling some sass…

Step 4: Set up a Gulp task to compile the style.scss file

Gulp allows you to code a series of tasks to “do” stuff. This is often boring things that will take up time. The cool thing is it also allows you to automate these tasks, but we’ll come to that later.

So, let’s assume you’ve got some sass in your style.scss file and you want to spit it out as a css file. You need a task to do that. If you don’t already have one, create a gulpfile.js in your project root. This is where all your tasks will go. The first thing we need to do in our gulpfile is initialise Gulp:

var gulp = require('gulp');

With that done, we can use the Gulp object to run the sass compilation, but first we actually need to install another module in Gulp to handle that. Run this from the terminal:

install gulp-sass --save-dev

We can now add a task into Gulp to grab the scss file, compile it and chuck it into the css folder as style.css. Firstly, initialise gulp-sass into a var:

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

Then create the Gulp task:

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

You should be able to see that is a straightforward looking piece of Javascript, nothing too scary. Basically, it’s setting up a Gulp task called “sass” which runs a funcation that grabs your scss file, pipes it through the gulp-sass module and throws it out into your css folder.

To run this, pop this in your terminal:

gulp sass

If that’s all working, you should see the following output:

[11:46:04] Using gulpfile C:\wamp64\www\prism_homepage\gulpfile.js
[11:46:04] Starting 'sass'...
[11:46:04] Finished 'sass' after 33

Well done – you’ve written your first Gulp task!

Step 5: Let’s automate that!

Running that task every time you make a change to your scss file will get to be a bore, but thankfully Gulp allows you to set up “watch” functions which fire tasks off if they detect changes in certain files. Add the following to your gulpfile:

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

Then run that from the terminal with:

gulp watch

That should start the watch going. Now any changes in style.scss will fire off the sass compilation function. Cool, huh? For now hit ctrl+c to stop the watch and get back to coding. We need to minify that css…

Step 6: Minifying is the bestifying

Reducing load times on web pages is great and we all love it. A good way to do that is including minified versions of your JS and CSS files. Gulp can do this for you, but we need a couple more modules installed. Run these to pop them in your project:

install gulp-cssnano
install gulp-rename

And initialise them with:

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

Now we need another task which will take our freshly minted css file and turn it into a min.css file:

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

After that, tweak your watch function:

gulp.task('watch', function(){
    gulp.watch('sass/**/*.scss', ['sass']);
    gulp.watch('css/**/*.css', ['minicss']);
});

Now the watch will compile the sass and then minify the compiled css. Link that min.css file into your html and your away! There’s a VS Code extension to run Gulp tasks, however I’ve found it has issues with the watch task, so you may want to keep running that from the terminal every time you start coding in your project.

This gives you a lot more flexibilty over your sass file makeup and you can start to use partials easily. Just create them as:

_mypartial.scss

In your sass folder, use:

@include "mypartial";

In your style.sass file and any change to the partial will fire the watch function, making the whole lot recompile. Really cool.

Your gulpfile should look like this:

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

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

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

gulp.task('watch', function(){
    gulp.watch('sass/**/*.scss', ['sass']);
    gulp.watch('css/**/*.css', ['minicss']);
});

EDIT: After publishing this I noticed that there was a few problems with the way the watch task was running. I’ve resolved these and added a new post to discuss the steps I took here…

And that’s it! Gulp is a really flexible and powerful way to automate workflow tasks so check it out. I’m still learning but I’ll be using it a lot more going forwards. Do check out that article I linked to – here it is again: https://css-tricks.com/gulp-for-beginners/. As I say, there’s a lot more really cool stuff in there that you might find useful. If this in itself helped you at all, don’t be a stranger- shout out in the comments!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s