Yogesh Chauhan's Blog

How to compress images with gulp in WordPress?

in WordPress on July 18, 2021

Follow first 3 steps from this post and install gulp and required packages.

How to install Gulp with WordPress?

Step 4: Plugin installation


npm install gulp-imagemin --save-dev

Step 5: Import the plugin


//gulpfile.babel.js
import { src, dest } from 'gulp';
import yargs from 'yargs';
import gulpif from 'gulp-if';
import imagemin from 'gulp-imagemin';

const PRODUCTION = yargs.argv.prod;

...
...

Step 5: Write a function


//gulpfile.babel.js
...
...
export const compressImages = () => {
  return src('assets/img/**/*.{jpg,jpeg,webp,png,svg,gif}')
    .pipe(gulpif(PRODUCTION, imagemin()))
    .pipe(dest('assets/img/compressed'));
}

Let’s discuss the function above.

As we saw in this compile and watch Sass with gulp post, using src we read the file and using dest we save the compressed images. yargs plugin is used to pass the –prod mode and using gulpif we add the conditions.

You can change the type of files in src as per your need. If you keep all types then it will search for all of those types.

This is how you can run the task by calling the function:


gulp compressImages


Step 6: Make it watch automatically

Let’s write another function using the watch from gulp.


//gulpfile.babel.js
...
...
export const watchImages = () => {
  watch('assets/img/**/*.{jpg,jpeg,webp,png,svg,gif}', compressImages);
}

This is how you can watch images:


gulp watchImages

After you run the command above, everytime you add a new image in that folder, it’ll compress it automatically!


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How to create a sticky menu pin using CSS?CSSHow to uninstall Cocoapods from the Mac OS?MiscellaneousHow to Recognize an Array in JavaScript?JavaScriptWhat’s new in WordPress 5.5?WordPressHow to scroll contents of HTML body horizontally and vertically using JavaScript?JavaScriptHow to convert an object from API to JSON array in Angular 9?Angular