Saul Salazar/Gulp, Automation with JavaScript

Created Tue, 19 Jan 2021 00:00:00 +0000

Leverage gulp and the flexibility of JavaScript to automate slow, repetitive workflows and compose them into efficient build pipelines.

What is gulp?

  • Command Line Interface(CLI) Tool
  • JavaScript Task Runner
  • Code-over-configuration
  • Data Streams
  • Open Source

Basically a tool for automating tasks like minification.

Benefits

  • Automate painful or time-consuming tasks
  • Complex tasks management
  • Easy to learn and simple to use
  • Consistent and high quality ecosystem (strict guidelines for plugins)
  • Everything can be processed in memory (streams)
  • Use npm modules to do anything you want
  • Over 2000 gulp plugins

Use Examples

  • Compressing images, css, html, js
  • SASS, LESS, Stylus
  • Jade, Marko, Handlebars, Dust
  • Transpiling JavaScript ES6, CoffeeScript, TypeScript
  • Unit testing with Mocha or Jasmine
  • CSS Autoprefixer (-webkit-transform)
  • Generating documentation with JSDoc
  • Code linting

Requirements

You must have NodeJS installed: click here to download nodeJS

Installation

  1. Install gulp globally
    $ npm i --global gulp-cli

  2. Initialize your project directory
    $ npm init

  3. Install gulp
    $ npm install --save-dev gulp

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

var gulp = require('gulp');

gulp.task('default', function() {
  // place code for your default task here
});
  1. Run the default gulp task
    $ gulp

Methods: 1. Define a task

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

// do stuff here

} );

Methods: 2. Watch files and do something when a file changes

gulp.watch( 'path', [ 'tasks', 'to', 'run' ] );

Methods: 3. Given a glob, get files

gulp.src( 'src/scripts/**/*.js' )

Methods: 4. Write files to disk

gulp.dest( 'path' )

Fundamentals

  • Plugins: Plugins are the means through which gulp accomplishes each process. Plugins are installed through npm and initiated using “require”.
  • Tasks: For Gulp, tasks always have a source and a destination. In between them lie the pipes that call each plugin and output the transmuted results to the next pipe.
  • Watchers: The watchers watch the source files for changes and call tasks whenever a change is detected.
  • gulpfile.js: This is the JavaScript file that the “gulp” command points at. It contains everything from the tasks to the watchers or other pieces of code used by tasks.

Globs

Globs are wildcard patterns that refer to files. Globs or arrays of globs are used as inputs in task source. Examples:

  1. *.scss: The * pattern is a wildcard that matches any pattern in the current directory. In this case, we’re matching any files ending with .scss in the root folder (project).
  2. **/*.scss: This is a more extreme version of the * pattern that matches any file ending with .scss in the root folder and any child directories.
  3. !not-me.scss: The ! indicates that Gulp should exclude the pattern from its matches, which is useful if you had to exclude a file from a matched pattern. In this case, not-me.scss would be excluded from the match.
  4. *.+(scss|sass): The plus + and parentheses () allows Gulp to match multiple patterns, with different patterns separated by the pipe | character. In this case, Gulp will match any file ending with .scss or .sass in the root folder.

Plugins List

# How to install plugins:
$ npm i --save-dev <plugin name>

# Example installing the plugin "gulp-sass"
$ npm i --save-dev gulp-sass

gulp-load-plugins

Get plugins from package.json and use them without require

var plugins = require('gulp-load-plugins')();

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

  return gulp
    .src( './**/*.js' )
    .pipe( plugins.uglifyjs() )
    .pipe( gulp.dest( './dest' ) );

} );

gulp-plumber

What Plumber does is catches errors and prevents the stream/pipe from stop.

// Global error handler
var gulpsrc = gulp.src;
gulp.src = function() {
  return gulpsrc
    .apply( gulp, arguments )
    .pipe( plumber( function( error ) {
      console.log( 'Error ( ' + error.plugin + '): ' + error.message )
      this.emit( 'end' );
    } ) );

};

gulp-util

Utility functions for gulp plugins.

  • log, colors
  • replaceExtension
  • isStream, isBuffer
  • noop() returns a stream that does nothing but pass data straight through.
.pipe(isProduction ? plugins.uglify() : gutil.noop())
gutil.log('stuff happened', 'Really it did', gutil.colors.magenta('123'));
gutil.replaceExtension('file.coffee', '.js')

gulp-rename

  • dirname: is the relative path from the base directory set by gulp.src to the filename.
  • basename: is the filename without the extension
  • extname: is the file extension including the ‘.’ like path.extname(filename).
  • prefix: “bonjour-”
  • suffix: “-hola”
gulp.src("./src/**/hello.txt")
  .pipe(rename(function (path) {
    path.dirname += "/ciao";
    path.basename += "-goodbye";
    path.extname = ".md"
  }))
  .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/hello-goodbye.md

gulp-header

Add a header to file(s) in the pipeline. Use Example: copyright.

// NOTE: a line separator will not be added automatically
gulp.src('./foo/*.js')
  .pipe(header('Hello'))
  .pipe(gulp.dest('./dist/'))

gulp-strip-comments

Removes comments from JSON, JavaScript, CSS, HTML, etc.

gulp.task('default', function () {
  return gulp.src('template.js')
    .pipe(strip())
    .pipe(gulp.dest('dist'));
});

gulp-watch

File watcher that uses super-fast chokidar and emits vinyl objects.

gulp.task( 'sass', function () {
  return watch( 'css/**/*.css', { ignoreInitial: false } )
    .pipe( sass() )
    .pipe( gulp.dest( 'build' ) )
});

gulp-if

  • Run tasks conditionally
  • if( condition, trueHandler, falseHandler )
var plugin = require( 'gulp-load-plugins' )();
var condition = true;

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

  return gulp
    .src( './src/*.js' )
    .pipe( plugin.if( condition, uglify() ) )
    .pipe( gulp.dest('./dist/') );

} );

gulp-sourcemaps

Automatically generating source maps for your minified Javascript, CSS files to debug them without having to use production versions.

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

  return gulp
    .src('src/**/*.js')
    .pipe(sourcemaps.init())
    .pipe(plugin1())
    .pipe(plugin2())
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('dist'));

});

gulp-uglify

  • UglifyJS is widely known as the most performant and effective JavaScript minifier available
var plugin = require( 'gulp-load-plugins' )();

gulp.task( 'minify.js', function () {

  return gulp
    .src( 'src/*.js' )
    .pipe( plugin.uglify() )
    .pipe( gulp.dest( 'build' ) );

} );

gulp-minify-html

var plugin = require( 'gulp-load-plugins' )();

gulp.task( 'minify.html', function () {

  return gulp
    .src( 'src/*.html' )
    .pipe( plugin.gulpMinifyHtml() )
    .pipe( gulp.dest( 'build' ) );

} );

gulp-minify-css

var plugin = require( 'gulp-load-plugins' )();

gulp.task( 'minify.css', function () {

  return gulp
    .src( 'build/css/*.css' )
    .pipe( plugin.gulpMinifyCss() )
    .pipe( gulp.dest( 'build/csss' ) );

} );

gulp-imagemin

  • Lossless compression ( no quality loss ).
  • Minify PNG, JPEG, GIF and SVG images.
  • Unsupported files are ignored.
gulp.task( 'minify.images', function() {

  return gulp
    .src( 'src/images/*' )
    .pipe( imagemin() )
    .pipe( gulp.dest( 'dist/images' ) )

} );

Gulp unCSS

  • can drastically reduce the weight of your css if you are working with frameworks like Twitter Bootstrap.
  • Only requires one argument and it can accept single files, globbing patterns and URLs.

Gulp unCSS

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

  return gulp
    .src( input.sass )
    .pipe( sass() )
    .pipe( concat('main.css') )
    .pipe( uncss( {
        html: [ 'index.html', 'posts/**/*.html', 'http://example.com' ]
    } ) )
    .pipe( gulp.dest( output.sass ) );

});

gulp-css-base64

Converts all data found within a stylesheet (those within a url( … ) declaration) into base64-encoded data URI strings. This includes images and fonts.

  • Supports local and remote resources.
  • Ability to specify a weight limit. Default is 32kB which is IE8’s limit.

gulp-css-base64

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

  return gulp
    .src( input.sass )
    .pipe( cssBase64() )
    .pipe( gulp.dest( output.sass ) );

});

Browser Sync

gulp.task( 'browser-sync', function() {
  browserSync.init( {
    server: { baseDir: CONFIG.BUILD.PATH },
    startPath: CONFIG.BUILD.INDEX, // index page of the server
    notify   : false, // send notifications inside the page
    open     : false // open web browser
  } );
} );

gulp.task( 'browser-reload', function() {
  browserSync.reload()
} );

gulp-documentation

Use gulp with documentation to generate great documentation for your JavaScript projects.

  • format: either ‘html’, ‘md’, ‘json’, or ‘docset’
  • filename: custom filename for md or json output
gulp.src('./index.js')
    .pipe(documentation({ format: 'md' }))
    .pipe(gulp.dest('md-documentation'));