Lab: Gulp Setup

Concepts: Introduction to Gulp

Overview

This lab shows you how you can automate tasks with gulp, a build tool and task runner.

What you will learn

  • How to set up gulp
  • How to create tasks using gulp plugins
  • Ways to automate your development

What you should know

  • Basic JavaScript, HTML, and CSS
  • Some experience using a command line interface

What you will need

  • Computer with terminal/shell access
  • Connection to the internet
  • A text editor
  • Node and npm

1. Get set up

If you have not downloaded the repository, installed Node, and started a local server, follow the instructions in Setting up the labs.

If you have a text editor that lets you open a project, open the gulp-lab/app folder. This will make it easier to stay organized. Otherwise, open the folder in your computer's file system. The app folder is where you will be building the lab.

This folder contains:

  • js/main.js and styles/main.css are sample resources that we use to experiment
  • index.html is the main HTML page for the sample site/application
  • gulpfile.js is the file that gulp uses to execute tasks, and where you will write your code

2. Install global tools

Gulp is available as a Node package. In this section we install the gulp command line tool on your system.

To install the gulp command line tool, run the following in the command line:

npm install --global gulp-cli

Explanation

This command installs the gulp command line tool (globally) using npm. We use the command line tool to actually execute gulp.

3. Prepare the project

All projects that use gulp need to have the gulp package installed locally.

From app/ (the project root), run the following in the command line:

npm init -y

Note that a package.json file was created. Open the file and inspect it.

From the same directory, run the following in the command line:

npm install gulp --save-dev

Note that a node_modules directory has been added to the project with various packages. Also note that package.json now lists "gulp" as a dependency.

In gulpfile.js, replace the TODO 3 comment with the following:

gulpfile.js

var gulp = require('gulp');

Explanation

We start by generating package.json with npm init (the -y flag uses default configuration values for simplicity). This file is used to keep track of the packages that your project uses, including gulp and its dependencies.

The next command installs the gulp package and its dependencies in the project. These are put in a node_modules folder. The --save-dev flag adds the corresponding package (in this case gulp) to package.json. Tracking packages like this allows quick re-installation of all the packages and their dependencies on future builds (the npm install command will read package.json and automatically install everything listed).

Finally we add code to gulpfile.js to include the gulp package. The gulpfile.js file is where all of the gulp code should go.

4. Minify JavaScript

This exercise implements a simple task to minify (also called "uglify" for JavaScript) the app/js/main.js JavaScript file.

From app/, run the following in the command line:

npm install gulp-uglify --save-dev

Now replace TODO 4.1 in gulpfile.js with the following code:

gulpfile.js

var uglify = require('gulp-uglify');

Replace TODO 4.2 with the following code:

gulpfile.js

gulp.task('minify', function() {
  gulp.src('js/main.js')
  .pipe(uglify())
  .pipe(gulp.dest('build'));
});

Save the file. From app/, run the following in the command line:

gulp minify

Open app/js/main.js and app/build/main.js. Note that the JavaScript from app/js/main.js has been minified into app/build/main.js.

Explanation

We start by installing the gulp-uglify package (this also updates the package.json dependencies). This enables minification functionality in our gulp process.

Then we include this package in the gulpfile.js file, and add code to create a minify task. This task gets the app/js/main.js file, and pipes it to the uglify function (which is defined in the gulp-uglify package). The uglify function minifies the file, pipes it to the gulp.dest function, and creates a build folder containing the minified JavaScript.

5. Prefix CSS

In this exercise, you add vendor prefixes to the main.css file.

Read the documentation for gulp-autoprefixer. Using section 4 of this lab as an example, complete the following tasks:

  1. Install the gulp-autoprefixer package
  2. Require the package in gulpfile.js
  3. Write a task in gulpfile.js called processCSS, that adds vendor prefixes to the app/styles/main.css and puts the new file in app/build/main.css

Test this task by running the following (from app/) in the command line:

gulp processCSS

Open app/styles/main.css and app/build/main.css. Does the box-container class have vendor prefixes for the display: flex property?

Optional: Read the gulp-sourcemaps documentation and incorporate sourcemap generation in the processCSS task (not in a new task).

Hint: The gulp-autoprefixer documentation has a useful example. Test by rerunning the processCSS task, and noting the sourcemap comment in the app/build/main.css file.

6. Automate development tasks

6.1 Define default tasks

Usually we want to run multiple tasks each time we rebuild an application. Rather than running each task individually, they can be set as default tasks.

Replace TODO 6.1 in gulpfile.js with the following:

gulpfile.js

gulp.task('default', ['minify', 'processCSS']);

Now delete the app/build folder and run the following in the command line (from app/):

gulp

Note that both the minify and processCSS tasks were run with that single command (check that the app/build directory has been created and that app/build/main.js and app/build/main.css are there).

Explanation

Default tasks are run anytime the gulp command is executed.

6.2 Set up gulp watch

Even with default tasks, it can become tedious to run tasks each time a file is updated during development. gulp.watch watches files and automatically runs tasks when the corresponding files change.

Replace TODO 6.2 in gulpfile.js with the following:

gulpfile.js

gulp.task('watch', function() {
  gulp.watch('styles/*.css', ['processCSS']);
});

Save the file. From app/, run the following in the command line:

gulp watch

Add a comment to app/styles/main.css and save the file. Open app/build/main.css and note the real-time changes in the corresponding build file.

TODO: Now update the watch task in gulpfile.js to watch app/js/main.js and run the minify task anytime the file changes. Test by editing the value of the variable future in app/js/main.js and noting the real-time change in app/build/main.js. Don't forget to save the file and rerun the watch task.

Explanation

We created a task called watch that watches all CSS files in the styles directory, and all the JS files in the js directory. Any time any of these files changes (and is saved), the corresponding task (processCSS or minify) executes.

6.3 Set up BrowserSync

You can also automate the setup of a local testing server.

From app/, run the following in the command line:

npm install browser-sync --save-dev

Replace TODO 6.3a in gulpfile.js with the following:

gulpfile.js

var browserSync = require('browser-sync');

Now replace TODO 6.3b in gulpfile.js with the following:

gulpfile.js

gulp.task('serve', function() {
  browserSync.init({
    server: '.',
    port: 3000
  });
});

Save the file. Now run the following in the command line (from app/):

gulp serve

Your browser should open app/ at localhost:3000 (if it doesn't, open the browser and navigate there).

Explanation

The gulp browsersync package starts a local server at the specified directory. In this case we are specifying the target directory as '.', which is the current working directory (app/). We also specify the port as 3000.

6.4 Put it all together

Let's combine everything learned so far.

TODO: Change the default tasks from minify and processCSS to serve.

TODO: Update the serve task to the following code:

gulp.task('serve', ['processCSS'], function() {
  browserSync.init({
    server: '.',
    port: 3000
  });
  gulp.watch('styles/*.css', ['processCSS']).on('change', browserSync.reload);
  gulp.watch('*.html').on('change', browserSync.reload);
});

Close the app from the browser and delete app/build/main.css. From app/, run the following in the command line:

gulp

Your browser should open app/ at localhost:3000 (if it doesn't, open the browser and navigate there). Check that the app/build/main.css has been created. Change the color of the blocks in app/styles/main.css and check that the blocks change color in the page.

Explanation

In this example we changed the default task to serve so that it runs when we execute the gulp command. The serve task has processCSS as a dependent task . This means that the serve task will execute the processCSS task before executing itself. Additionally, this task sets a watch on CSS and HTML files. When CSS files are updated, the processCSS task is run again and the server reloads. Likewise, when HTML files are updated (like index.html), the browser page reloads automatically.

Optional: In the serve task, add minify as a dependent task. Also in serve, add a watcher for app/js/main.js that executes the minify task and reloads the page whenever the app/js/main.js file changes. Test by deleting app/build/main.js and re-executing the gulp command. Now app/js/main.js should be minified into app/build/main.js and it should update in real time. Confirm this by changing the console log message in app/js/main.js and saving the file - the console should log your new message in the app.

Congratulations!

You have learned how to set up gulp, create tasks using plugins, and automate your development!

Resources