Create your account

Already have an account? Login here

Note: By joining, you will receive periodic emails from Coursetro. You can unsubscribe from these emails.

Create account

Live Reload with the Gulp Task Runner (with Bootstrap, Foundation, etc)

By Gary simon - Sep 18, 2017

A common concern for frontend developers is setting up live browser reloading when they make updates to their CSS/Sass, HTML and other files.

Fortunately, there's a Javascript task runner called Gulp.js which makes setting this all up a breeze. So, let's get started!

If you prefer watching a video tutorial

Be sure to Subscribe to the Official Coursetro Youtube Channel for more development videos.

Prerequisites

You're going to need Nodejs with NPM (Node Package Manager) installed before proceeding. You can check whether or not you have them installed by visiting your command line/console and typing:

$ node -v

$ npm -v

If either of these commands go unrecognized, you need to visit Nodejs.org and download the appropriate installer based on your OS.  By default, the installation will include NPM.

Once finished, reload your console and you can rerun the above commands which should provide you with a version number.

Starting a Project

 In your console, let's create a new project folder:

$ mkdir project101
$ cd project101

Next, we're going to run the following command:

$ npm init

This will prompt us with a series of questions, which will ultimately generate a package.json file. You can hit [enter] through all of the prompts until you get back to the command line.

Installing Gulp and Browsersync

We're going to use NPM to install several packages. At the very least, we need the Gulp task runner package and Browsersync, which is what enables the automatic browser refreshing.

Run the following command:

$ npm install gulp browser-sync --save-dev

More often than not, you will likely want to utilize the power of Sass when you're developing a project. If you're using a framework that's built to work with Sass (such as Bootstrap, Foundation or Bulma), or if you simply want to use Sass without a framework, then you need to install another package that can compile the Sass files to CSS.

If this is the case, run the following command:

$ npm install gulp-sass --save-dev

If you're using a different preprocessor such as Stylus for instance, simply Google the name of the preprocessor + gulp and chances are, there will be a gulp-specific package for it.

Installing a Frontend CSS Framework

If you're planning on using one of the several popular frontend frameworks, such as Bootstrap, Foundation or Bulma, then now is the time to install those packages (assuming there's one).

For this tutorial, we'll assume it's Bootstrap 4, though the process is pretty much the same for other popular frameworks:

$ npm install bootstrap@4.0.0-alpha.6

Creating the Project Folder & File Structure

At this point, your folder should consist of just a node_modules folder and the package.json file.

In the project root, create an index.html file with the following contents:

<!DOCTYPE html>
<html class="no-js" lang="en">
    <head>
        <title>Bulma</title>
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link media="all" type="text/css" rel="stylesheet" href="/css/main.css">
    </head>

    <body>
        <h1>My awesome project</h1>
    </body>
</html>

The only thing of importance is the stylesheet we're referencing at /css/main.css - We don't need to create this folder or file, as it will be automatically generated when the sass compiler works its' magic.

Next, let's create a new folder called sass and a file inside of it called main.scss:

@import 'node_modules/bootstrap/scss/bootstrap';

$mycolor: blue;

body {
    background: $mycolor;
}

Here we've added some simple sass and a single ruleset, to ensure that our compiling works correctly. At the top, this is where we import bootstrap.

Setting up the Gulp File

The last order of business is to create a file named: gulpfile.js in the project root. To begin, we start with importing the packages we installed earlier via npm:

var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();

Next, we need to create a few tasks that will handle compiling and browser reloading via BrowserSync. 

The first ask we'll create will handle the sass compiling:

var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();

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

First, we're naming the task sass, then we're returning a source file named main.sass. If you have multiple sass files inside of the sass folder, you could use an asterick instead of explicitely naming the file.  For instance: ./sass/*.sass. You can also reference multiple folder locations by placing them in side of an array, like: ['location1', 'location2', etc..].

 

Next, we use the .pipe method to call the sass compiler. 

After that, we run gulp.dest to place the compiled CSS to a new folder. In this case, it will transform main.sass to main.css.

Finally, we call browserSync.stream() which will refresh the browser after the CSS has been compiled.

Next, we'll create another task to create a local server through BrowserSync, and watch any sass and HTML files:

var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();

gulp.task('sass', function() {
    return gulp.src('./sass/main.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./css'))
        .pipe(browserSync.stream());
});

gulp.task('serve', ['sass'], function() {
    
    browserSync.init({
        server: "./"
    });

    gulp.watch("./sass/main.scss", ['sass']);
    gulp.watch("./*.html").on('change', browserSync.reload);
});

This task is called serve, and we're creating a server at the root ./.

Then, we're using gulp.watch to watch our single sass file (note that you can use * for multiple files). If main.sass is changed, it will call the sass method.

We use the same method to watch HTML files, which will reload the browser if it's updated.

Finally, we have one more simple task to create:

var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();

gulp.task('sass', function() {
    return gulp.src('./sass/main.scss')
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./css'))
        .pipe(browserSync.stream());
});

gulp.task('serve', ['sass'], function() {
    
    browserSync.init({
        server: "./"
    });

    gulp.watch("./sass/main.scss", ['sass']);
    gulp.watch("./*.html").on('change', browserSync.reload);
});

gulp.task('default', ['serve']);

This final task at the bottom simply means that when gulp is ran at the command line within the project folder, it will call the serve task by default. This negates having to type: gulp serve explicitely.

Giving it a Go

If you set everything up correctly, all you need to do is run the following command when you want to start developing your project:

$ gulp

It should automatically load up your browser and show you an ugly, vibrant blue colored background! If so, everything has worked.

You can experiment with the live reloading by making a change and saving to your sass files and html files.

You can add to your gulpfile by integrating many other packages for different purposes. You can include javascript files, CSS minification packages, and more!

Hopefully you learned a lot here, enjoy!


Share this post




Say something about this awesome post!