1.12. Working with Gulp

Gulp is a command line tool which uses Node.js and can be used to declare and execute tasks. The tasks can be used to automate some of the repetitive tasks of the development environment. We can use Gulp to automate things like compiling, compressing files or refreshing a web page in a browser after saving some changes.

How to do it…

All the tasks are configured in a JavaScript file known as gulpfile.js, let’s create that file in a new folder. Once you have created the file,

  1. You will require all the plugins that we will use in the next few recipes:
    const gulp = require('gulp'),
    source = require('vinyl-source-stream'),
    buffer = require('vinyl-buffer'),
    browserify = require('browserify'),
    tsify = require('tsify'),
    sourcemaps = require('gulp-sourcemaps'),
    tslint = require('gulp-tslint'),
    uglify = require('gulp-uglify'),
    typedoc = require('gulp-typedoc'),
    runSequence = require('run-sequence'),
    webserver = require('gulp-webserver'),
    header = require('gulp-header'),
    rimraf = require('rimraf');
  2. You also need to generate a package.json file:
    $ npm init
  3. And install all those packages as development dependencies using npm:
    $ npm install gulp vinyl-source-stream vinyl-buffer browserify tsify gulp-sourcemaps gulp-tslint gulp-uglify gulp-typedoc run-sequence gulp-webserver gulp-header rimraf
  4. After installing all the necessary dependencies, we can start creating some tasks. The following code snippet can be used as an example of a really basic task:
    gulp.task("hello", function() {
      console.log("hello world!");

How it works…

As you can see, this task has a name "hello":

gulp.task("hello", function() {
  // ...

The task also has console logic (logs some text in console):

gulp.task("hello", function() {
  console.log("hello world!");

In real life a task, we can perform many complex operations.

There’s more…

It is common to see many hard-coded paths and other settings in the gulpfile.js, which is a problem if in the future, you need to change your project’s directory structure or if you want to re-use the build script on a new project. One solution is to separate the settings (magic strings and constants) from the Gulp task logic:

gulp.task("task_name", function () {

  // configuration
  const input  = "...";
  const output = "...";

  // logic
  return gulp.src(input)

Source Code

Working with Gulp

See also

Before proceeding to the next recipe please note that this example and many more can be found online at https://github.com/kushwahashiv/Typescript2xCookbook.

Shiv Kushwaha