Use gulp-imagemin with imagemin-jpeg-recompress plugin?

I am just experimenting with Gulp to just optimize the images. I believe imagemin-jpeg-recompress reduces JPGs more than the default optimizer that comes with gulp-imagemin . I'm wondering if there is a way to use gulp-imagemin

but replace the plugin jpegtran

for imagemin-jpeg-recompress

.

I cannot find detailed docs on how this might work together.

+3


source to share


2 answers


I'm going to answer my own question. I could be wrong, but it seems to be a simple process. Just a require

plugin (in this case, I want to use a plugin imagemin-jpeg-recompress

). Then specify the plugin to use in imagemin

using the property use

imagemin

. I believe this will override the optimizer jpegtran

that ships with imagemin

.



var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var imageminJpegRecompress = require('imagemin-jpeg-recompress');

gulp.task('optimize', function () {
  return gulp.src('src/images/*')
    .pipe(imagemin({
      use:[imageminJpegRecompress({
        loops:4,
        min: 50,
        max: 95,
        quality:'high' 
      })]
    }))
});

      

+4


source


In newer versions (3.x) gulp-imagemin, the solution above does not work. The reason is that they changed how plugins are declared and configured for array syntax and range arguments.

API change documented in 3.0.0

gulp.task('default', () => {
    return gulp.src('src/images/*')
-       .pipe(imagemin({
-           interlaced: true,
-           progressive: true,
-           optimizationLevel: 5,
-           svgoPlugins: [{removeViewBox: false}]
-       }))
+       .pipe(imagemin([
+           imagemin.gifsicle({interlaced: true}),
+           imagemin.mozjpeg({progressive: true}),
+           imagemin.optipng({optimizationLevel: 5}),
+           imagemin.svgo({plugins: [{removeViewBox: false}]})
+       ]))
        .pipe(gulp.dest('dist/images'));
 });

      

Noting that also "if you are passing an array of plugins, you need to explicitly pass every plugin you want, not just the ones you want to change."



Newer versions of imagemin-jpeg-recompress (5.x) follow this API.

Putting it all together using the default plugins (except for jpegtran, which we override with jpeg-recompress), the above answer can be formatted like this:

var gulp = require('gulp');
var imagemin = require('gulp-imagemin');
var imageminJpegRecompress = require('imagemin-jpeg-recompress');

gulp.task('optimize', function () {
  return gulp.src('src/images/*')
    .pipe(imagemin([
      imagemin.gifsicle(),
      imageminJpegRecompress({
        loops:4,
        min: 50,
        max: 95,
        quality:'high' 
      }),
      imagemin.optipng(),
      imagemin.svgo()
    ]))
});

      

Relevant discussion gulp-imagemin github tracker question

+4


source







All Articles