sajad torkamani

What is Gulp?

Gulp is a JavaScript automation tool that lets you automate slow, repetitive tasks. You can write custom tasks using an expressive JavaScript syntax or utilize the rich ecosystem of community plugins.

Setup Gulp

Install the gulp CLI tool:

npm i -g gulp-cli

cd into your project and install Gulp as a dev dependency:

npm i -D gulp

Example task

Create a gulpfile.js file at the root of your project:

const { src, dest } = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');

exports.default = function() {
  return src('src/*.js')
    .pipe(babel())
    .pipe(src('vendor/*.js'))
    .pipe(uglify())
    .pipe(dest('output/'));
}

Run:

gulp

Run tasks

Run default exported function from gulpfile:

gulp

Run specific function from gulpfile:

gulp <task-name>

List tasks

Print the task dependency tree for the loaded gulpfile.

gulp -T

Print a plaintext list of tasks for the loaded gulpfile.

gulp --tasks-simple

Run tasks in sequence

const { series } = require('gulp');

function transpile(cb) {
  // body omitted
  cb();
}

function bundle(cb) {
  // body omitted
  cb();
}

exports.build = series(transpile, bundle);

Run tasks in parallel

const { parallel } = require('gulp');

function javascript(cb) {
  // body omitted
  cb();
}

function css(cb) {
  // body omitted
  cb();
}

exports.build = parallel(javascript, css);

Combine series and parallel tasks

const { series, parallel } = require('gulp');

function clean(cb) {
  // body omitted
  cb();
}

function css(cb) {
  // body omitted
  cb();
}

function javascript(cb) {
  // body omitted
  cb();
}

exports.build = series(clean, parallel(css, javascript));

Signal completion of task

You can resolve a Promise to signal that a task has completed:

function promiseTask() {
  return Promise.resolve('the value is ignored');
}

exports.default = promiseTask;

See docs

Or, invoke the callback (passed to all tasks) without no arguments:

function callbackTask(cb) {
  // `cb()` should be called by some async work
  cb();
}

exports.default = callbackTask;

Execute tasks on file change

const { watch } = require('gulp');

exports.default = function() {
  // The task will be executed upon startup
  watch('src/*.js', { ignoreInitial: false }, function(cb) {
    // body omitted
    cb();
  });
};