Example GULP File

Gulp is a task runner designed for coders. There are many things that gulp can do, from compile sass into minimized css to optimizing your images.

Today I'd like to show you how to write a simple gulp file which will compile our sass, minify and concat our code!

Folder Setup for Project

The following is a simple generic folder setup for your project.

All your source js and sass will be kept in the src folder, and the dist folder will hold your optimized files for production.

  • app
    • src
      • js
      • sass
    • dist
      • css
      • js
  • gulpfile.js
  • node_modules
  • package.json

Optmize CSS with GULP

My favorite thing to do with Gulp is to handle my css files. Sometimes this is all I need depending on how simple the project is. So before we can use Gulp, we need npm and node. So make sure you have read the basics on setting up node with your site.

So let's go head and create a gulpfile.js in the same directory as your package.json, which should usually be in the root directory of your project.

So as you can see in the comments above, the first line in the styles task is to set our source which is in the /app/src/sass folder. The *.scss tells us that any file that ends with scss is a sass file.

The next pipe, we run sass which creates our css from sass. After minifying, we concat our css into one file named main.css. Concatenating css and js is explained in detail below.

The line after this minifies this css, so that we decrease our filesize, increasing our speed.

And the last line simply places main.css file into our production css folder.

Optimize Javascript with GULP

There isn't really a lot of difference between the styles task and the scripts task. We take all the js files in the src/js folder and concatenate them, uglify them and put them into the dist folder.


Another great use for grunt is concatenation! For every css and js file that is referred to in your html, there is a certain amount of overhead. If you have 10 css files, then your site will certainly run slower than if you combined those 10 css files into 1. This is also true for your javascript files.

But if you have one huge css file, then working in it could become a problem! Specially if you work as part of a team! So that's where concatenation comes in! You can keep your source files separated for ease of use, but combine them into one file for production!

Final gulpfile.js

Now we put our two tasks together, so we can run them with one task. We will also add a "watch" which will check for any changes in our source folder. If you make a change in the js or sass, the watcher will automatically optimize your changes into your dist folder. Tools such as phpstorm already do this, but I like to use gulp for this to keep things simple!

Here is our completed gulpfile.js. All you need to do is run gulp into the terminal, and your'e ready to develop like a pro!