”;
In this chapter, you will learn how to optimize images. Optimizing will reduce the size of the images and assist in faster loading.
Install Plugins to Optimize Images
Go to “work” directory from your command line and install “gulp-changed” and “gulp-imagemin” plugins by using the following commands.
npm install gulp-changed --save-dev npm install gulp-imagemin --save-dev
Declare Dependencies and Create Tasks
In your configuration file gulpfile.js, first declare the dependencies as shown in the following command.
var gulp = require(''gulp''); var changed = require(''gulp-changed''); var imagemin = require(''gulp-imagemin'');
Next, you need to create tasks for optimizing images as shown in the following code.
gulp.task(''imagemin'', function() { var imgSrc = ''src/images/*.+(png|jpg|gif)'', imgDst = ''build/images''; gulp.src(imgSrc) .pipe(changed(imgDst)) .pipe(imagemin()) .pipe(gulp.dest(imgDst)); }); gulp.task(''default'',[''imagemin''],function(){ });
The imagemin task will accept png, jpg and gif images from src/images/ folder and minify them before writing it into the destination. The changed() ensures that only the new files are passed in each time for minifying. The gulp-changed plugin will only process the new files and hence utilized precious time.
Run the Tasks
The configuration file is set up and ready to execute. Use the following command to run the task.
gulp
On running the task using the above command, you will receive the following result in the command prompt.
C:work>gulp [15:55:49] Using gulpfile C:workgulpfile.js [15:55:49] Starting ''imagemin''... [15:55:49] Finished ''imagemin'' after 23 ms [15:55:49] Starting ''default''... [15:55:49] Finished ''default'' after 23 μs [15:55:54] gulp-imagemin: Minified 1 images (saved 558.3 kB - 8.3%)
”;