gulpjs is a new kind of taskrunner. It is like gruntjs but much better. The work of a taskrunner is to automate simple tasks like minifying files, compiling preprocessor css like less, etc.
This is how I started using gulpjs
gulpjs
As I said before, gulpjs is a taskrunner. It is based on streams the technicalities of which are beyond me but that means it is extremely fast.
But better than this, the api of gulpjs is straightforward meaning you can get up and started within minutes.
This is how my gulpfile looks like :
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
gulp.task('compress', function() {
gulp.src('assets/js/*.js')
.pipe(uglify())
.pipe(concat("all.js"))
.pipe(gulp.dest('dist'));
});
gulp.task('default', ['compress']);
Pretty simple huh? gulpjs is much easier to use and this was one of the main reasons I started using it instead of gruntjs
Getting started
First, you will need nodejs. Once installed, start npm via the command prompt and install gulpjs globally. This is because you can start calling it anywhere.
npm install -g gulp
Done?
Now, add devDependencies in your package.json which should be in your project’s root. For this example, I am using gulp-uglify and gulp-concat.
The required task is to minify and then concat all javascript files.
package.json :
{
"name": "example",
"version": "0.1.0",
"author": "shash7",
"devDependencies" : {
"gulp-uglify": ">= 0.2.0",
"gulp-concat": ">= 2.1.7"
}
}
Now give the command ‘npm install’ inside the project root (where you package.json will be residing) After installing, make a file named gulpfile.js inside the project root.
// Dependencies
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
// The actual task. Note the pipe function
gulp.task('compress', function() {
gulp.src('assets/js/*.js')
.pipe(uglify())
.pipe(concat("all.js"))
.pipe(gulp.dest('dist'));
});
// The default task
gulp.task('default', ['compress']);
After adding the dependencies, you will need to create a task. I have named my task compress which is exactly what it does. gulpjs needs a task called default which will be executed when you run the file. Inside the default task, call your task inside an array. If you want, you can also bind a callback function.
When everything is done, simply call gulp in your project’s root
gulp
That’s it. gulpjs will now check for js files inside a folder called js and then will minify and concat them all and place them inside a folder called dist and will name the new file as all.js
That’s all for now. I hope you find gulpjs as awesome I did.