Gulp.js Flashcards
What’s the command line syntax for running tasks?
gulp
if no task name given, runs “default” task name.
Start a gulp file with a default task.
What’s the file name?
How to run the task?
What’s the syntax for creating a task?
// gulpfile.js var gulp = require("gulp");
gulp.task(“default”, function () { … });
// command line gulp
// syntax for creating a task // notice that you can include optional array of dependency tasks to run first gulp.task("task-name-no-spaces", ["dep-task-1, "dep-task-2"], function () { ...});
Take a glob (file structure)
gulp.src("relative/path/**/*.css") //=> recursively (thanks to **) returns all css files (thanks to *.css) // argument can also be an array of strings, if desired
Pipe output to plugins + pipe to output files
var gulp = require("gulp"); var minify = require("gulp-minify");
gulp.src(“file/path/.css”)
.pipe( minify() ) //=> pipe to plugins, notice the function is invoked
.pipe( gulp.dest(“file/path/.min.css”) ); //=> pipe to output files
// gulp.dest will write piped input to files. If the previous plugin kept the files as separate files, will write as separate files; else if the plugin merged them (say, for production), they will write to a single file, so be mindful of how the previous plugin is sending output. // can also write multiple times, like so:
gulp.src("src/templates/**/*.jade") .pipe(jade()) .pipe(gulp.dest("build/templates")) .pipe(minify()) .pipe(gulp.dest("public/templates-min"));
Watch file(s) for change and run tasks when change occurs.
gulp.task(“watch”, function () {
// first arg can be a string or array of files to watch for // second arg is an array of tasks to be fired OR can be a function gulp.watch("path/**/*.js", ["tests"]);
});
Error handling
Plugins can throw errors, which is caught by the .pipe() method and execution stops. If you would like to catch an error:
gulp.src(“…”).pipe(minify()).on(“error”, function (err) { … })
However, this error handling works on only the previous plugin. To add generic error handling to all plugins, use plumber
plugin (must come first):
gulp.src(“…”).pipe(plumber()).pipe(minify());
Run mocha tests when a file changes?
var gulp = require("gulp"); var gutil = require("gulp-util"); var mocha = require("gulp-mocha"); var should = require("should");
gulp.task(“test”, function () {
return gulp.src(“test/**/*.js”, { read: false }) // NOTICE the read:false
.pipe( mocha({
reporter: “list”,
globals: { should: should } // Now tests need not to require should
}).on(“error”, gutil.log);
});
gulp.task(“watch”, function () {
gulp.watch([“lib//.js”, “test/**/.js”], [“test”]);
});
Grab command line parameters when running gulp
// command line gulp print-name --name "Julie Chubbs"
// gulpfile.js var gulp = require("gulp"); var args = require("yargs").argv;
gulp.task(“print-name”, function () {
console.log( args.name ); //=> “Julie Chubbs”
});