1

Good day!

I want to automate the conversion of images to webp format. To avoid doing it manually or via online converters, I decided to use gulp 4 and gulp-webp.

This is the structure of nesting folders in my project:

enter image description here

I want Gulp, when it finds a picture, so that it creates a folder called "webp" at the same nesting level and places the converted picture in this folder.

I want the following result:

enter image description here

My Gulpfile.js:

let gulp = require('gulp'),
    webp = require('gulp-webp');

gulp.task('webp', () => {
    // './dev/img/**/*.{png,gif,jpg}' - all files in img and all files in subfolders in img


    return gulp.src('./dev/img/**/*.{png,gif,jpg}')
        .pipe(webp())
        .pipe(gulp.dest(gulp.src)) //something like this, but it doesn't work

    }
);
Mark
  • 143,421
  • 24
  • 428
  • 436
Alexei
  • 277
  • 1
  • 2
  • 9

1 Answers1

2

This can be done with the help of gulp-rename.

To install gulp-rename run:

npm i -D gulp-rename

Then in your gulpfile.js add the import:

const rename = require('gulp-rename');

Then change your stream like this:

return gulp.src('./dev/img/**/*.{png,gif,jpg}')
    .pipe(webp())
    .pipe(rename({ prefix: 'webp/' }))
    .pipe(gulp.dest('./dev/img'));

The prefix option inserts "webp/" before the bare filename after the dest target "./dev/img".

GOTO 0
  • 42,323
  • 22
  • 125
  • 158
  • This code in the img folder creates a webp folder and in it it already creates a hierarchy as in img (the only difference: files in webp format). But I need a webp folder to be created with each image at the same nesting level, and this image converted into webp should be placed in this folder. I wrote in the description of the question what result is needed (second picture). – Alexei Dec 08 '21 at 20:09
  • 1
    @Konstantin Ah okay, I misunderstood that part. I've updated my answer now. – GOTO 0 Dec 08 '21 at 21:13
  • 2
    No need for the `, { base: './dev/img' }` parameter since that is what `base` would be set to automatically anyway. – Mark Dec 08 '21 at 22:57