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 Browsersync using Gulp

Beginner’s guide to Browsersync using Gulp

If you have never heard of Browsersync… Oke. What can I do? You haven’t. Not your fault, tho. Let me quickly sum up what it does.

If you check out their web page, you’ll see this line right on the top:

Time-saving synchronised browser testing

I couldn’t state it better. Browsersync is the awesome web development assistant that’s going to help you live-reload the page every time you save/change something. Imagine this:

You have 1 screen. You have to alt+tab to get to the browser, then click F5, then a few seconds later you see what you did, oke, you don’t like it? alt+tab to get back, rinse, repeat. We probably all know know how this looks like.

BuT WHat if we can make a shortcut?

Instead of doing this process 10x a minute… We can just click ctrl+s and and have the amazing Browsersync do the boring stuff for us! It’s like having an extra hand or something!

Lemme show you how it looks like first:Browsersync in action

Neat-o. If you’re following along since the start of this three part tutorial, you’re all set. If not, here’s a few snippets of what you’ll need:

Directory structure we’re using is:

And gulpfile.js should look like this at this point:

Don’t forget to install gulp and gulp-sass into your project so we can actually leverage this. If you’re battleborn veteran in these series, don’t worry about it.

If you’re not sure what all this means, I recommend checking out tutorial 1 and tutorial 2 of this 3-part series on Gulp and how to make it rock your world and make you a faster and better web developer! 🙂

Now let’s get down to browsersync, shall we?

Before we start leveraging the awesome power of the Browsersync, we gotta pull it into our project. As usual, npm install is the way to go:

Notice the --save-dev flag here. That states that we only need this tool in development. Next, we gotta instruct gulpfile to use it and we’ll right away create a new instance of Browsersync:

Now, our favorite browser refresh tool needs a bit of setup in order for it to work on our local development environment. First of all, the .create() at the end of the require is basically telling browsersync to quickly whip up a server. Browsersync needs one in order to work. At this point, you don’t need to know pretty much anything about the servers in order to configure it. The only thing that it actually requires is the folder root, so to speak, in which the server will start. So, it looks like we need a little configuration in our gulpfile. Here’s the snippet:

We’re calling upon the .init and we’re instructing it to use the server with baseDir in “application” folder. Nice.

The next step would be to just slightly append to the sass task that we have already. We gotta let it know that once the task is run, we also want to ‘reload‘ the page. Here’s how the ‘sass’ task will look like now:

The reload method will inform all browsers about changed files and will either cause the browser to refresh, or inject the files where possible.

At this point, we’re all good! We’re all set… sort of. If we could somehow run both watch and browserSync server tasks at the same time in the same bash window or cmd or terminal, yeah, this would work. However, these tasks start processes that occupy that terminal/bash/cmd, and we can’t use it for other things. Sooooooooo, there’s something we can do, and we should leverage an additional parameter in the gulp watch which will state what task must be run in order for watch to start. Lemme show you:

And maybe you would wanna watch for any html file edits, maybe javascript edits, all that good stuff. Let’s append that there, as well!

Now if you revert to the lil’ gif on top that I showed you, you’d get those results! kA-BooOOoM! #magic. ^_^

Lemme just real quick recap what we’ve managed to accomplished:

  1. We’ve installed Gulp
  2. We made it sing along the most Sass(y) tune ever an use sass (d’oh)
  3. We have a vigilant file watcher to stand guard and update the code once save happened
  4. We’re live reloading pages!
  5. We’re faster in our frontend task duties, hence, better developers!

Play around! Explore! You have a hefty html file to play with! Try adding more styles! Changing stuff! See how it feels for you, once you’re 2-3 minutes into all this, you’ll never try to go back to plain alt+tab, F5, alt+tab routine again.

throwing in a lil’ extras

I am preparing an optional tutorial that you’re gonna love, as well. Usually frontend developer’s task doesn’t simply end up with creating awesome code. Our duties are to concatenate and minify our scripts so they can be as tiny as possible and production-ready! I’ll throw a link to the lesson here once it’s done! 🙂

And congrats! Hopefully this 3-part series in gulp has thought you a little more about how fun development can be, upgraded your knowledge base and made you a better developer! Cheers! 🙂

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

Install NodeJS & NPM on your machine

Install NodeJS & NPM on your machine

Before I start explaining WHY you really need NodeJS and NPM (Node Package Manager) on your machine NOW, lemme first share just why it’s a must, especially for a frontend developer like yourself.

Pain… explain(ed).

You see, I grew up in a world where CSS preprocessors were a myth. A great unknown. Nothing. Less… Sass… All these cool things didn’t exist. Everything we had at our disposal was plain CSS. Like this:

Yeeeeeyyy, that’s awesome! I could change the color of my text. Not so impressive once 2000s hit the door with a slam and wrecked their way into the web development world. Suddenly, websites required more. Oke, say I have a section (it was all divs back then) with an id of #hero and it had two areas that had to be 9to3 ratio and then different margins and padding and signup form and all that was to be ONLY for the specific #hero area? OK, game on:

Yeah. div#hero .right form #email is exactly what every developer loves to do. Then – SASS came in and everything was amazing… Your code could have looked like this now:

Much better, right? But we had to use pre-processor to use that, right? And how the heck can we do that?

Answer came to me when I found out about Gulp. Oh. My. God. I was instantly 10x faster on coding. Variables, mixins and all the cool stuff I always wanted to have when developing awesome looking web pages have opened another dimension for me in world of frontend development. NPM is the way to go! And lemme tour you down real quick how to install it, and you can check out my article on how to install Gulp in your project and start leveraging the awesomeness of today’s technologies, like Sass or Less.

Enter Node

First of all, if you’re on OS X or Windows,  the most painless method of installing NodeJS and & NPM is through their website.

node and npm home page

I recommend installing the LTS (long term support) version of Node, but if you feel bold to explore, go ahead and get the most recent (current) version. Keep in mind that having the LTS version pretty much guarantees that most of the packages are working.

Once you download the installer and run it, you’ll see that Node is checking out the space requirements… Which can take a few moments to complete.

Node Installer computing space requirements

Click next -> next -> next -> confirm and agree on terms -> next a few times, and installment will proceed. Windows might ask you to confirm and there you go. Node (and NPM alongside) should be ready to use on your computer.

You can go ahead and open up CMD or Terminal to check out if the installment was all good. To open CMD on Windows, press the windows key and start typing cmd, then click enter.

Check Node and NPM

You can type out those two commands to verify that Node and NPM are installed successfully! In the coming tutorials we’ll leverage the power of NPM and we’ll start to rock out hard at the modern frontend development!

Cheers, laddies!