Gulp - Using
In the previous chapters, you have studied about Gulp installation and Gulp basics which includes build system of Gulp, package manager, task runner, structure of Gulp etc.
In this chapter, we will see the basic things for developing application:
Declaring required dependencies
Creating task for the dependencies
Running the task
Watch the task
Dependencies Declaration
When you are installing plugins for the application, you need to specify dependencies for the plugins. The dependencies are handled by the package manager such as bower and npm.
Let's take one plugin called gulp-imagemin to define dependencies for it in the configuration file. This plugin can be used to compress the image file and can be installed using below command line:
npm install gulp-imagemin --save-dev
You can add dependencies to your configuration file as shown below:
var imagemin = require('gulp-imagemin');
The above line includes the plug-in and it is included as an object named imagemin.
Creating Task for Dependencies
Task enables a modular approach to configuring Gulp. We need to create task for each dependency which we would add up as we find and install other plugins. The Gulp task will have following structure:
gulp.task('task-name', function() {
//do stuff here
});
Where task-name is a string name and function() that performs your task. The gulp.task registers the function as a task within name and specifies the dependencies on other tasks.
You can create the task for above defined dependency as shown below:
gulp.task('imagemin', function() {
var img_src = 'src/images/**/*',
img_dest = 'build/images';
gulp.src(img_src)
.pipe(changed(img_dest))
.pipe(imagemin())
.pipe(gulp.dest(img_dest));
});
The images are located in src/images/**/* which are saved in the img_src object. It is piped to other function created by the imagemin constructor. It compresses the images from src folder and copied to build folder by calling dest method with an argument which represents the target directory.
Running the Task
Now Gulp file is setup and ready to execute. Just run the following command in your project directory to run the task:
gulp imagemin
Run the task by using the above command, you will get to see below result in the command prompt:
C:\work>gulp imagemin [16:59:09] Using gulpfile C:\work\gulpfile.js [16:59:09] Starting 'imagemin'... [16:59:09] Finished 'imagemin' after 19 ms [16:59:09] gulp-imagemin: Minified 2 images (saved 80.81 kB - 16.9%)