Gulp can be used to perform different types of tasks.To automate tasks we define tasks in Gulp.In these tasks we use the npm plugins.There are npm plugins for different types of tasks.For example there are plugins for
- Minifying files
- Unit testing JS code
- LESS css preprocessor
- Running module bundlers such as WebPack
You can check the available plugins here plugins
Here we will see how to perform some of the common tasks using Gulp.
Minifying file using uglify plugin
Minifying file means compressing the file so that extra characters such s spaces and unused characters are removed.This is of much significance specially in web applications.This is because bandwidth is a very critical aspect of web applications.So reducing size of files even up to few kbs may impact performance.
To get idea baout how to define tasks in gulp please go through the following .
Before we can use the mify plugin we need to install the plugin using npm.We can install the plugin by executing the following command from within the project directory:
npm install --save-dev gulp-uglify
Once the uglify plugin is installed we will add the following code to the gulpfile.js file.Following will define a task called minify.This task is reading files defined in the js directory within the main directory.The output of gulp.src() method is passed to the uglify plugin by using pipe().
Passing the output of one method to next is very useful when using gulpfile to define tasks.
var gulp = require('gulp'), uglify = require('gulp-uglify'); gulp.task('minify', function () { gulp.src('js/Greet.js') .pipe(uglify()) .pipe(gulp.dest('minified')) });
The above task will minify all the files defined in the js directory and put the output in the minified directory.If you see the minified directory you can see that it contains the minified files corresponding to the files defined in the js directory.
Concatenate files
To concatenate all the JavaScript files in a single file we will use the concat plugin.To use the concat plugin we need to install the dependency of the plugin in project.json file as:
npm install --save-dev gulp-concat
Add the following code in the gulpfile.js.
gulp.task('minify', function () { gulp.src('js/*.js') .pipe(concat('main.js')); .pipe(uglify()) .pipe(gulp.dest('minified')) });
The ‘minify’ task will first concatenate all the .js files in the js folder to a file called main.js.It will then minify the main.js file.
Copy files from one location to another
To copy files from one location to another we can use the src() and dest() functions.The following task will copy the files from the js folder to the copy folder:
gulp.task('copy', function () { gulp.src('./js/*.*') .pipe(gulp.dest('./copy')); });
Leave a Reply