”;
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 basics for developing an application, which includes the following −
- Declaring required dependencies
- Creating task for the dependencies
- Running the task
- Watching 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 the following command line −
npm install gulp-imagemin --save-dev
You can add dependencies to your configuration file as shown in the following code.
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 for configuring Gulp. We need to create a task for each dependency, which we would add up as we find and install other plugins. The Gulp task will have the following structure −
gulp.task(''task-name'', function() { //do stuff here });
Where ‘task-name’ is a string name and ‘function()’ 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 the above defined dependency as shown in the following code.
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 is saved in the img_srcobject. 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
Gulp file is set up and ready to execute. Use the following command in your project directory to run the task −
gulp imagemin
On running the task using the above command, you will see the following result in the command prompt −
C:work>gulp imagemin [16:59:09] Using gulpfile C:workgulpfile.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%)
”;