Follow first 3 steps from this post and install gulp and required packages.
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!
command-line compression guide gulp images task runner