Tutorial

How To Get Started with Gulp.js on your VPS

Published on February 19, 2014
How To Get Started with Gulp.js on your VPS

About Gulp.js


Gulp.js is a task runner that can help your front-end developing experience greatly. The purpose of a task runner is to automate tedious tasks that you have to do over and over again in the course of a project. Grunt.js is another such popular task runner that many developers are using for automating frontend processes.

Gulp.js uses code over configuration for setting up its tasks and this makes it very easy to maintain for the project. Additionally, it uses Node.js streams which makes it very fast. A key difference between Gulp and Grunt is that instead of setting up an input/output for each plugin, Gulp pipes through all the set up plugins the source files to then produce the destination files.

For a great article on setting up Grunt.js, this tutorial is a great read.

In this tutorial, however, we will install Gulp.js on our VPS and set up a small project to illustrate how easy it is to automate tasks. For this I assume you already have Node.js installed together with NPM (Node Package Manager). If you don’t already, you can get started with this tutorial.

Installation


Installing Gulp.js is actually quite simple. Since we’re using NPM, all you have to do is run the following command:

npm install gulp -g

This will install Gulp.js gloablly on your VPS and make it available for you in the command line. It follows that we set up our individual project for which we add Gulp plugins as needed.

Our project


In order to illustrate the power of Gulp, we will start a small frontend project called Gus and focus on styling issues. Let’s thus create our project folder and navigate inside:

mkdir Gus
cd Gus

A nice thing about the Node Package Manager is that you can declare what libraries you need for the project in a package.json file that you can then commit to your version controlled repository. You can create this file manually or use a command line utility to do so. We’ll go with the second option because it’s safer in terms of not making any syntax mistakes. Run the following command and follow the instructions on the screen:

npm init

My new package.json file looks like this after following all the defaults and setting a description for my project.

{
  "name": "Gus",
  "version": "0.0.0",
  "description": "My Gus project",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "BSD-2-Clause"
}

It can contain less than this but also a lot more (as we will see in a second).

Now that we have our package.json file, we can add our Gulp.js libraries to the project and have them automatically included in this file as devDependencies. But first, what libraries do we want to use?

For the purpose of this tutorial, we will stick to the following task: compile sass files, autoprefix the resulting css files with vendor prefixes, and then minify them.

For Gulp to be able to compile the Sass files, you’ll need to first install Ruby, Ruby Gems and Sass on the VPS. You can quickly take care of that with the following commands:

sudo apt-get update
sudo apt-get install ruby-full rubygems
sudo gem install sass

Next, run the following command to install Gulp in our project and save it as a devDependency:

npm install gulp --save-dev

Next, run the following command to install the libraries needed to perform the tasks I just mentioned:

npm install gulp-ruby-sass gulp-autoprefixer gulp-minify-css gulp-rename --save-dev

A couple of things you’ll notice after running these commands: (1) there is a new folder in your project root called “node_modules” that contains all the installed packages and (2) the latter are referenced in the package.json file as devDependencies.

Setting up the tasks


All the tasks and requirements for them need to be set up in a file called gulpfile.js located in the root of your project. So create it and paste in the following block:

var gulp = require('gulp'),
    sass = require('gulp-ruby-sass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss = require('gulp-minify-css'),
    rename = require('gulp-rename');

As you can see, we create some variables in which we require all the libraries I mentioned above. You’ll notice an additional one called “rename” that will help us rename files.

Below this declaration, we can now create our tasks. Although you can create multiple tasks and even have them run each other, we will now create only one called styles:

gulp.task('styles', function() {
  return gulp.src('sass/*.scss')
    .pipe(sass({ style: 'expanded' }))
    .pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1'))
    .pipe(gulp.dest('css'))
    .pipe(rename({suffix: '.min'}))
    .pipe(minifycss())
    .pipe(gulp.dest('css'));
});

Above we use gulp.task to generate a new task called “styles”. Its callback is “gulp.src” that locates the source files the task will be performed on. In our case the .scss files located in the sass/ folder in the project root. These files are in turn piped through Gulp plugins and sent to their destination set by gulp.dest.

In other words, this tasks will take all the .scss files from that folder and compile them to css before running them through autoprefixing. The resulting files will then be placed in the css/ folder. Then the same files are copied and renamed with a .min suffix at the end and run through the minifying plugin and placed in the same css/ folder.

To test this out, create the two folders (sass and css) and create a .scss file in the sass/ folder called “styles.scss”. Inside, place the following statements:

$color: #eee;

#box {
  color : $color;
  box-sizing: border-box;
}

As you can see, this is some basic SASS syntax which contains a CSS property that is not yet prefixed. Let’s run our Gulp.js styles task to turn this into what we need. From the project root folder, runt the following command:

gulp styles

You should get something like this in the terminal window:

[gulp] Using file /path/to/project/Gus/gulpfile.js
[gulp] Working directory changed to /path/to/project/Gus
[gulp] Running 'styles'...
[gulp] Finished 'styles' in 224 ms

Now if you check in the css/ folder, you’ll notice 2 files: style.css and style.min.css. The second one should contain the minfyed version of the first one which should contain the following css code:

#box {
  color: #eeeeee;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

Readily compiled and prefixed so you don’t have to worry about that anymore. And the minifyed version is on standby as well. Now this is already awesome, but let’s see how we can have Gulp watch for changes in our .scss files and run the task as the files are being saved. This will essentially save us even the trip to the command line for running the task.

For this, we’ll need to create a new task below the existing one:

gulp.task('watch', function() {

  // Watch the sass files
  gulp.watch('sass/*.scss', ['styles']);

});

This will essentially be a task that watches over changes to the files in a specified folder and runs tasks when this happens. The task we set to run in our case is styles. Now we need to run the watch task from the command line:

gulp watch

And this will keep watching the respective folder for changes and running the styles task until we stop it:

ctrl + c

Conclusion


In this tutorial, we’ve seen how to set up Gulp.js in a frontend project and use it to run automated tasks with high convenience. Its powers do not stop here as there are a multitude of plugins available that you can use in your tasks. You can manipulate javascript files and even images and set up tasks that run other tasks for even more automation.

<div class=“author”>Article Submitted by: <a href=“http://www.webomelette.com/”>Danny</a></div>

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
5 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Please update with latest instructions. Running gulp styles returns the following error.

TypeError: glob pattern string required
    at new Minimatch (/root/Gus/node_modules/gulp-ruby-sass/node_modules/minimatch/minimatch.js:116:11)
    at setopts (/root/Gus/node_modules/gulp-ruby-sass/node_modules/glob/common.js:114:20)
    at new GlobSync (/root/Gus/node_modules/gulp-ruby-sass/node_modules/glob/sync.js:40:3)
    at Function.globSync [as sync] (/root/Gus/node_modules/gulp-ruby-sass/node_modules/glob/sync.js:26:10)
    at /root/Gus/node_modules/gulp-ruby-sass/index.js:68:21
    at Array.forEach (native)
    at gulpRubySass (/root/Gus/node_modules/gulp-ruby-sass/index.js:67:10)
    at Gulp.<anonymous> (/root/Gus/gulpfile.js:9:11)
    at module.exports (/root/Gus/node_modules/orchestrator/lib/runTask.js:34:7)
    at Gulp.Orchestrator._runTask (/root/Gus/node_modules/orchestrator/index.js:273:3)

It appears as if others are having similar issues with this tutorial: Stack Overflow asked by VOA Stack Overflow asked by msmolcic

Problem

The error being thrown by gulp is related to a post-css npm module. Since you are using sass, I’m not sure why this is there. Try removing it and post your package.json file.

According to the docs, you don’t want to use pipe in that first declaration according to the gulp-ruby-sass. Try this instead:

// Styles Task
gulp.task('styles', function () {
    return sass(paths.sassSrcPath, {
            style: 'compressed',
            loadPath: [paths.sassImportsPath]
        })
    .pipe(gulp.dest(paths.sassDestPath));
});

more in-depth info

Use gulp-sass instead of gulp-ruby-sass. It’s a much faster, better supported version of Sass at this point in it’s dev cycle.

This is how I usually use gulp-sass in a styles build task (based off of Yeoman generator gulp-webapp):

gulp.task('styles', () => {
  return gulp.src('app/styles/*.scss')
    .pipe($.sourcemaps.init())
    .pipe($.sass.sync({
      outputStyle: 'expanded',
      precision: 10,
      includePaths: ['.']
    }).on('error', $.sass.logError))
    .pipe($.autoprefixer({browsers: ['last 1 version']}))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/styles'))
    .pipe(reload({stream: true}));
});

It’s similar to yours but it outputs sourcemaps, which are super helpful when you are debugging compressed code. You’d have to add gulp-sourcemaps to your package.json to get this to work.

If you are looking to automate deployment then Flightplan is probably a better choice:

https://www.npmjs.org/package/flightplan

@ben.miles2 When I’m ready to deploy, I have a bash script that downloads the latest version of my project from github. It then runs my grunt (you can replace with gulp of course) tasks that copies all final files to my published folder that my DO server is pointing to.

I have this all automated with a php file that calls this bash script so whenever I’m ready to deploy to production, I just commit my latest version to github, and visit a URL.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
March 8, 2014

@ben.miles2: As long as gulp.js supports scp, I don’t see why not.

Can you use Gulp.js to deploy to DO? So it would SCP from a dist folder locally to your app folder on the VPN?

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel