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

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
How to implement NSNumberFormatter in Swift for currency?SwiftHow to Skip or Exclude a Specific URL or File From .htaccess Rewrite Rule?PHPHow to create and store JSON objects in localStorage using JavaScript?JavaScriptHow to create HTML elements with ID and class using JavaScript?HTMLapply_filters function in WordPressWordPressDynamically generate names in SCSS (animation example)SCSS