Select Page
Setting up Gulp and Sass

Setting up Gulp and Sass

SASS (Syntactically Awesome Stylesheet)

It is a blessing. Whoever works frontend development for more than a couple of years will tell you the exact same thing. Gulp is a tool that we’ll use to convert and pre-process SASS (or SCSS) into the plain CSS that browsers understand and we’ll make it look like a piece of cake.

“If you think math is hard, try web design.” – Thrish Parr

Inspiring quote to begin with. Now off to work.

Gulp is a build tool which can help you out in a number of tasks when it comes to web development. More often than not, it is on duty with some of these tasks:

  • Compiling CSS with preprocessors like SASS or LESS
  • Optimizing assets
  • Live-reloads when a file is edited/saved
  • Create a quick web server

This doesn’t even scratch the surface of what you can do with Gulp, but it’s quite possible where it finds the largest use. Even thou it’s not too complicated, you’ll still have to learn to really use the Gulp to create tasks, and I’ll give you a hand here.

First of all, why gulp?

Gulp is not the only build tool you can use. There’s a whole army of tools with similar options, Grunt and Brunch to name a couple. The main reason why I love Gulp is because of it’s simplicity.  Configurations with Gulp tend to be quite a breeze, and lemme show you, but first, let’s install Gulp. Make sure you have NPM installed, if you don’t, check out my guide for installing it here.

Next, open up your cmd (as an admin) or terminal, and type:

If you’re on Mac or Linux, you should add sudo as the first word of the code. Like this:

That will enable the global gulp command you can run in the terminal.  (that’s why we used the -g flag)

Let’s create our project, shall we?

Before anything else, let’s create a folder where we’ll host our little experiment, and these ‘test’ folders I like to call “experiments”.
Note, I’ll be using git bash on Windows machine. You have been warned.
All righty. Let’s start by creating a folder experiment in our root and initiating npm project: (you still have terminal running, right?)

This is what you’ll get:

After npm init

Feel free to hack and slash your keyboard with enter key, all the info submitted here.  Awesome. Start your favourite editor into the experiment folder, or use Vim like I do here (a bit higher learning curve on this one, tho). Vim is integrated into the Git bash, so I’ll just use that to make certain edits.

Right now, you have created your npm entry point -> package.json . This folder is where npm looks into and does it’s actual package managing, and a lot more I won’t cover in this lil’ tut.

Next thing, back in the experiments folder, time to install Gulp into the project. This is separate from the global installment of gulp, which we use to run commands. This what we install right now is our ‘staging ground’ for gulp tasks, so to speak. So let’s do it:

Please not the difference that the –save-dev flag has been used here. This means we’ll only use Gulp in development, not in production. Let’s see what that command did. Here’s a screenshot:

With node_modules folder

A-ha! New folder. NPM will use node_modules folder to store all project dependencies, so never-ever manually delete that folder. Important stuff.

Next, let’s just quickly assume we’re gonna have certain folder tree for our experiment. Here’s a list of files/folders you can create:

So, in a lot of projects, actual web site is not served from the root of the project, and we won’t assume that either. Let’s assume our app will run from ‘application’ folder. And don’t forget the gulpfile.js. This is what we’re focusing on this lesson.

My first task

Time to SASS it up? Almost. Let’s open up the gulpfile.js first. And before starting to write gulp tasks, you need to “require” it. JavaScript folks are familiar with this, I’m sure. This is how you use the actual npm packages.

So, once open, enter this line of code in the first line:

The very basic syntax for using gulp is this:

So the task name, the ‘name-of-the-task’ parameter there is what you’ll type out once you start gulp from the termina/bash. Let’s start with fundamental “hello” message:

Let’s go back to terminal and see the fruit of our labor! Enter:

This should be the result of what you’ll get in the terminal:

gulp heya

Awesome! Let’s make it more exiting!

SASS with Gulp

First of all, in order to compile SASS into the CSS, we’ll need a middleware package called gulp-sass. The way we install this is quite simple, really, back to terminal, into the root “experiment” folder and let’s npm install it!

Next stop, if you didn’t guess it, we gotta ‘require’ it into our gulpfile, like this:

Just add it on top, line 2 of the file. Next, last step, we need sass/scss file, right? Create ‘styles.scss‘ file under ‘application/scss/‘ directory.

Now SASS is at our reach! Let’s setup a basic sass/scss compiler:

Let’s create something scss specific into our styles.scss file:

Go back to the root, where your gulpfile is, and run gulp sass command!

run gulp sass

BOOM! Fireworks! National anthem! Cheerleaders cheering! Birds birding… y’know what I mean!

Let’s navigate to our /application/css/ file and see what we have here:

finished task sass

Congrats are in order! You have successfully setup your preprocessor and you can use sass (or scss, whichever syntax you prefer) in your projects!

Stay tuned for additional tutorials on how we can make even more usability out of Gulp! Someone said “Automatic browser refresh upon file save“…?

Click to continue with this series of tutorials…

Beginner’s Guide To Sass – Preprocessing

Beginner’s Guide To Sass – Preprocessing

Sass is a preprocessing language. Means – it needs tools to make it work. Imagine there as a middleman who’ll take no share whatsoever. Even as a bonus it can do some more stuff to help you out!

by performing preprocessing, think of code compiling

You need a compiler to do it, and in the case of the following lecture, we’ll roll out with the original, the first of it all – Ruby. If you wanna set up a Sass preprocessing tooling chain with Gulp, I’ve got you covered right here, too.

I’ve opted up for Ruby in this series because it’s the one universal tool you can use to very easily setup everything and it takes just a few clicks. And it all started here, too.

Mac

If you’re on Mac – congrats. Ruby comes preinstalled. The only thing you gotta do is install the Sass gem.

Please note that if something fails, you should try with sudo command. Easiest Sass installment of it all. 🙂 Go ahead and check it out with sass -v.

Linux

Many distros already come with Ruby packed in. Give it a go by typing in the terminal: ruby -v. If you don’t have Ruby installed:

If you have it already up and running, check for Sass as well by typing
sass -v. If you get a version number, you’re good. Otherwise:

Windows

Getting Ruby on Win machine can be a bit tricky, as you’d have to setup environmental variables and edit path yourself and stuff. Easiest thing to do is to get the latest installer here and let Windows take care of all of that.

Once completed, you can check it out by opening up your CMD (easiest – click on windows key, type cmd and click enter) and type:

You should be all good to go at this point. However, one more thing, since my days on development under Windows’ harsh jurisdiction has been painful, I strongly recommend you to get Git Bash. Windows is not really so optimized for development and for coding like Linux or Mac, so you’ll need all the help you can get. 🙂

Start of the journey

All righty! You’re all set! One last thing to consider is – in case you don’t wanna use terminal and command-line inputs to start off preprocessing, you can use Koala GUI interface to run tasks. I’m hoping you’re hardcore like I am, and I hope you’ll be typing out stuff before defaulting to GUI clients… Takes up more RAM, in all honesty. 🙂

Step 1:

Choose your editor

There’s a whole arsenal of editors and IDEs (Integrated Development Environments) you can use. I use Atom. Atom is good. Atom is love. Others I’d recommend are Sublime and Brackets. If you’re really into the world of pain, you can use Vim. Extremely high learning curve, tho.

Step 2:

Organize your folders before you start

This is quite important point that most of the developers don’t give enough attention to. I usually work from Laravel (that’s my weapon of choice for server-side framework) and it comes out with serious boilerplate already shoved in, so I don’t have to think too much about folder structure. But if you’re starting from scratch and building things on your own (like we’ll be doing here), then let’s make a plan. Here’s the folder structure:

Aaaaaand let’s keep it like this for now. Create your experiment folder and dig in, open up the editor and create those folders. I’ll wait here.

Step 3:

Running the preprocessing watcher in sass

Now – you’re ready to embrace this journey. Let’s put some content first into the main.scss file:

The indentation that you see here is valid SCSS code. Don’t worry about it. We’ll cover it pretty soon.It’s here just so we know we did in fact hit the ground running. Let’s add up some basic boilerplate for our app/index.html file:

Now, if you’re in a root folder of your lil’ project, you can run following command from the terminal/bask/cmd:

What this’ll do is it’ll start the Sass job, --watch for changes in the sass/main.scss file and output it in the app/css/main.css file! If you open up the index.html file right now in your browser (just double click on it), you’ll see a compelling, moral boosting message to get you started with a nice dark green background and white text font.

woo hoo! all done!

Believe it or not, you just setup your first Sass job using Ruby compiler! You can set up a style of the output by appending --style compressed at the end of the sass command line, you can make it lose all the space it can and output it all on a single line:

All the styles you can:

  1. nested
  2. compact
  3. expanded
  4. compressed

You can turn off warnings with --quiet flag. You can watch multiple files but load only a single file with something like this:

There are tools like Compass, Gulp and a full arsenal of others that can help this look a lot more better… but since we’re starting… we start of from the ground up!

That’s all folks, I’ll see you soon with more, and next stop will be Sass variables!

Beginner’s Guide To Sass Basics

Beginner’s Guide To Sass Basics

So now that you’ve finally decided to learn some Sass basics, and finally took a bold step forward in digging out my site, let’s first introduce you to what Sass is and all it’s goodies.

SASS – Syntactically Awesome Style Sheets

Yeah. Mouthful. And first time I read it was “synthetically” style sheets. My bad, I guess. Basically, Sass is a preprocessor that introduced so much goodies to the plain ol’ CSS, that I’m pretty sure I’m never going back. Basically it’s to the CSS what Typescript Coffeescript (Kudos to Redditor Myrad for correcting me here) is to JavaScript. Sort of. All right, let’s get down to it.

I am gonna list and explain most of what it does here, and then we’ll move on to individual “lessons” that’ll go in depth and explain everything.
So, here’s what Sass brings to the table:

  1. Introduction
  2. Preprocessing
  3. Variables
  4. Nesting
  5. Partials
  6. Imports
  7. Mixins
  8. Inheritance
  9. Operators

Introduction

Sass logo

The Sass in it’s basic form is in my honest opinion confusing.

Sass has two different syntax, so to speak. Original (Sass) was brought into existence back in 2006, Hampton Catlin, and just like his other project (HAML) was built for Ruby on Rails, so was Sass. Basically, they both shared the same syntax that didn’t include any brackets. Kinda confusing when you look at CSS, really. Here’s an example:

I had experience with HAML, YAML, Stylus and other similar syntax, so this was not really too confusing, but still, when we came down to operators, mixins, all that didn’t really float my boat anymore. And it was a little hard for me to get used to, as I didn’t have to use ; to end the code anymore! Then came Sass version 3, and SCSS syntax was introduced, which is pretty much just extension to CSS, bringing in all the power of Sass to it! Literally, everything you write in CSS is a valid SCSS as well! Obligatory example:

See? Just like CSS. All righty, moving on.

Preprocessing

This is the gist of it. CSS on it’s own is interesting, but as your stylesheets are getting piled up and fat with monstrous code… You need a way to whip monstrous code into shape, right? Sass allows you to use a lot of features (see the list a bit above? Everything under point 2). Of course, in order for it to actually work, you need to install Ruby on your machine, or if you’re into GUI Sass compilers, Koala (Windows, Linux and Mac supported) is excellent and totally free. You can also go through my Gulp tutorials and setup a nice tooling chain to get you up and running in no time!

In our examples here, we won’t get much into the gulp (as I have it explained already), we’ll go Ruby-way here. Here’s a nice guide on how to install Ruby on your machine.

Cool! Off to those Sass basics! In the individual tuts that are coming I’m gonna explain how to setup Ruby to process Sass. 🙂

Variables

Variables in Sass are quite the same thing as in any other languages… They store info to use later on in different functions. In these reusable variables you can store anything, really, like other CSS values, colors, font stacks and so on. We use $ here to declare a variable (if you are familiar with PHP, you’re right at your home!). Example:

Once Sass is processed, the variables will resolve in exactly this:

One important note to take here is that variables won’t be processed into the actual code. The $primary-font and $body-background are just for your Sassy usage.

nesting

This is my crush. This is that gal I wanted to take home after every night out. First, let’s have a look real quick at HTML. If you open up developer tools in any page, you’ll see a well structured code, nicely indented, you can pretty much see an ordered hierarchy of elements and easily distinguish which “child” elements belong to which “parent” elements. CSS is flat. Really, it is. Not like my type of girls.

Let’s have a look at the example of nesting:

Now those are the curves I like! (laugh, please, this is the best joke I have for tonight) Keep note tho: Folks recommend not to go wild on this feature. If it’s 4 steps in, that’s plenty. Time to rethink what your doing.

All this nice and fancy nesting will result in the end code like this:

Isn’t that what we write for every single project? That very code? :p

Partials

CSS already has a way of importing other stylesheets. Only problem is, every time you do this, you will have your server make another HTTP request. Not great for page speed reviews, right? Well, sass has a same feature, @import, which will pull in the _partial.scss files (note the _) and combine all that nice code into the code where you made the import call and then process it into a single stylesheet. Better!

Say you have a partial with variables, or reset, or any other piece of code. Let’s go with reset example!

Now let’s pull it in!

The resulting, processed and refined single CSS file will look like this:

Mixins

Imagine JavaScript functions. It looks like this, right?

Now, Sass mixins allow you to do the exact same thing: take a piece of “functionality” or “style” and use it elsewhere. This saves countless hours on repetition and copy/paste work. Imagine you have 10 different buttons, but they all have border-radius property set? In case you didn’t know, if you wanna go full-browser compatibility, you gotta add up -webkit, -moz, -ms and ocassionally -o (blaaaaaah) in front of some properties. Like border radius! Let’s save time by introducing mixins!

So by saying @mixins and then later on “calling that function” with @include we can save a lot of space in our editor, right?

Inheritance

This is exactly what it means. Other classes (or IDs, mind you) can extend FULLY another class. This is extremely useful on – again – buttons! For example, let’s say you have an array of buttons in your arsenal, for different occasions, of course. Example (continued from previous):

Last but not the least:

Operators

Math in CSS… witchcraft? In Sass, quite all right and finally welcomed!  Sass has a handful of standard math operators like +, -, *, /, and % ! Very useful for setting widths, for example. Let’s say you have a 1200px wide container. You’d wanna split it into percentage parts for it’s child elements, right?

This is your very first grid, believe it or not. 🙂

sass basics – explained

This is pretty much an overlay of what Sass basics are. I will be adding up individual/partial tutorials on all the stuff explained here soon, my tempo is just 2 (maybe 3) tuts a week, so stay tuned and we’ll learn quite some more of SASS – SYNTACTICALLY AWESOME STYLE SHEETS!

Gulp watch – Transpile Sass to CSS on the fly

Gulp watch – Transpile Sass to CSS on the fly

Gulp watch is the command that will stare without blinking at your files and detect saves upon those files. #stalker-detected

All jokes aside…

This is a serious matter. Imagine if you could only click ctrl+s and have files compiled, transpiled, minified, whatever you wanna do instantly without going back to the terminal and running gulp sass …? Yeap. I know your pain.

First of all… We’re going to continue onward from this tutorial. If you have not already completed it – just do it. (I am not affiliated with Nike in any way)
If you completed it already and have the files on hand… let’s dig right in!

First of all, globals explained

Globals in Node (hence, Gulp as well), or globs as everyone refers to them, are file pattern detection expressions that allow you to mass select certain file types (for example). Simplest example would be *.scss, which will totally select only Scss files we have in certain folder.

Most of the projects, depending on their size, of course, will not require you to know more than 3 or 4 such globs. I personally usually use only the last one in the following list.

  1.  *.sass <- This syntax is the most simple way to select a file, irrelevant on the file’s actual name, and relies on the file’s directory location.
    • Pros: Gives you more control on the sass files that are actually going to be watched/worked with
    • Cons: You’re limited to keep all scss files in one folder. I think it’s oke, but for massive framework builds, who wouldn’t wanna have this directory structure:
      |--sass
      |----mixins
      |----components
      |----variables
      |----vendors

      …list goes on. 🙂
  2. *.+(scss|sass) <- This structure will enable you to watch for multiple extensions/patterns as specified. This specific script can go ahead and watch for file saves on both scss and sass files. You can add up more extensions followed by the | (pipe) symbol.
    • Pros: Gives you more flexibility on the pattern and type of what you wanna glob for
    • Cons: None really
  3. !avoid-me-I-stink.scss <- This syntax that has the ! mark in front will tell the watcher not to include this file. In most of the programming languages the ! means the word not, really, or negation of some sort.
    • Pros: If there are files that shouldn’t be included into the gulp watcher method, for example, this is the way to go
    • Cons: Files’ feelings get hurt, you know, for being left out
  4. **/*.scss <- This is the glob I use the most. It’s an upgraded version of the regular *.scss glob, where it states to search the scss files in the current directory and all sub-directories. This is the one that saves your day.
    • Pros: Having the glob that will look for all file types that are ultimately going to compile to assets in ALL directories and it’s subs is the bread and butter of faster workflow
    • Cons: Careful if you have vendor files. You generally don’t wanna change these and then compile them. (*cough, bootstrap*)

Now that we know of globbing, let’s just quickly expand our sass task from gulpfile.js:

Awesome! Now we can move on and effectively compile all Sass/Scss files in the application/scss directory. Let’s try it out?

I’m gonna add up another file to the scss folder. Let’s call it button.scss, add up random stuff, and let’s run gulp sass command! I’ll open up Atom editor and git bash and take one snapshot to show how it goes:

Sass with multiple files

Awesome! On the left you see that the file is compiled, transpilled, copied into the css folder and all that good stuff we wanted to do.

Enter gulp watch

The general syntax for Gulp watcher is actually surprisingly simple, it’s as plain as:

First parameter in the watch function is which file (or files. #globbingpower) to watch, and then in the next parameter you’ll include an array of tasks to run. Let’s now create a gulp watch task:

Basically, we’re creating a task and letting Gulp know he’s gotta keep an open eye on changes to the application/scss/**/*.scss files. If, in this case, any of the .scss files are changed, run the “sass” task that we already have. Lemme show you how the complete gulpfile.js looks like right now:

Give it a whirl. Type gulp watch in the root experiment directory:

Gulp watch running

All right! We have a file watcher in place! Try changing something in any of the *.scss files we have:

gulp watch executes

Woo-hoo! Congrats are in order, again, you’ve set up your very first file watcher using Gulp! This is quite sufficient to run all of your sass compiling, but we only have one more thing to do here, and that is error handling.

Nobody likes watcher errors, right?

So let’s handle them! First, lemme show you how an error looks like with gulp watcher:

Gulp watch error

Oh snap! Now what? Gulp is helpful enough to let you know what went wrong, but the most annoying thing that actually happened is that our watcher stopped. It just bailed on us… Let’s expand our gulpfile a liiiiiiiitle more to see if we can remedy this, and complete this tut.

First, we gotta tell gulp to watch for errors. Gulp has certain events built in, and they’re handled by adding up .on in the pipe workflow. Example:

Oke. This will tell gulp that on case of error, use the custom function showError that I’m about to spill out for you:

Right! Full gulpfile.js right now:

Let’s run our gulp watcher again, and this time I’ll simulate an error by adding up five exclamation marks (!!!!!) to the end of the code. So gulp watch in the terminal, and now save the file with error:

Gulp watch error handled

And there we go! You’ll notice that the gulp “pipe” didn’t break this time, and watcher didn’t stop! You can examine the error, correct it, write proper scss/css and save, and everything will compile!

that’s all folks…

You now have a functional file watcher that’ll keep an open eye on your files, update your regular CSS files and log any errors it encounter along the way!

Stay tuned, next time we’ll see how to have browser refresh itself on file watch. #magic

Click here to continue with this series