How would you use Gulp to optimize images?

Gulp, a task runner in JavaScript, can be used to optimize images by automating the process. This is achieved through plugins like gulp-imagemin which minifies PNG, JPEG, GIF and SVG images.

Firstly, install Gulp and gulp-imagemin using npm (Node Package Manager). The command line would look something like this :
npm install --save-dev gulp gulp-imagemin​

Next, create a ‘gulpfile.js’ at your project root. Inside this file, require both Gulp and gulp-imagemin:

var gulp = require('gulp');
var imagemin = require('gulp-imagemin');

Then, define a task that sources all images from a directory, pipes them through the image optimization function, and outputs them into a destination folder:
gulp.task('images', function(){
    return gulp.src('src/images/*')
        .pipe(imagemin())
        .pipe(gulp.dest('dist/images'))
});​​


Finally, run the ‘images’ task from the command line with gulp images. This will start the image optimization process.