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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
What’s Interpolation in SCSS (Sass)?SCSSHow to Use Aggregate Functions (MIN, MAX, SUM, AVG, COUNT) to Summarize Data in SQL?SQL/MySQLThe Lending Club Analysis using Logistic Regression and Random Forest in RStudioMiscellaneousWordPress: How to create a folder if it doesn’t already exist?WordPressHow to create a smooth scrolling effect with CSS?CSSHow to create a link tag button using CSS?CSS