dots Created with Sketch.
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

import { src, dest } from 'gulp';
import yargs from 'yargs';
import gulpif from 'gulp-if';
import imagemin from 'gulp-imagemin';



Step 5: Write a function

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

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.

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

#Jul 22 Is there a CSS parent selector? #Jul 22 Difference between :where and :is in CSS #Jul 22 Does :is() pseudo selector hint at CSS preprocessing in the future? #Jul 22 Control Scrolling with CSS Scroll Snap #Jul 21 Control rendering using CSS content-visibility property #Jul 21 How to use @supports rule in CSS?
You might also like these
5 Key Principles Of Good Website UsabilityUI/UXHow to create a function in SCSS (Sass)?SCSSArray destructuring and Object destructuring in JavaScriptJavaScriptHow to control file extensions with an .htaccess file?MiscellaneousHow to change the Login Logo in WordPress?WordPressHow to get the height and width of an element using JavaScript?JavaScript