Monday, June 6, 2016

Gulp from command line with error handling


First step is installing the gulp.
Install gulp
Install gulp modules

There will be node-modules directory in your present working directory (pwd).

Create a gulpfile.js in your current working directory which would include the JS functions and gulp tasks.
------------------------------------
Sample gulpfile.js
------------------------------------
function handleError(err) {
    console.log("Error: ", err.toString());
    process.exit(-1);
}

var gulp = require('gulp');
var minifyCss = require('gulp-minify-css');

gulp.task('minify-css', function() {
  return gulp.src('./*.css')
    .pipe(minifyCss({compatibility: 'ie8'}))
    // handle error
    .on("error", handleError)
    .pipe(gulp.dest('CSS'));
});

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

gulp.task('minify-js', function() {
  return gulp.src('./*.js')
    .pipe(uglify())
    // handle error
    .on("error", handleError)
    .pipe(gulp.dest('JS'))
    ;
});



Open terminal in the directory where gulpfile.js is located.
Run the following command.
gulp <task-name>
Ex. gulp minify-js


Error handling

Error code returned from the gulp process will be handled in the shell script that invoked the gulp command.

On error, there will be an exit code of -1 from gulp handleError function which can be used to take corresponding action in the shell script.

----------------------------------------------
Sample shell script (powershell)
----------------------------------------------
gulp minify-js
if ($LASTEXITCODE -ne 0) {
    throw "Gulp Failed. Refer gulp log files."
    exit
}
echo ":) Gulp tasks finished successfully."

No comments:

Post a Comment