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

2.8k views Asked by At

I'm just experimenting with Gulp to simply optimize images. I find that 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 swap out the jpegtran plugin for the the imagemin-jpeg-recompress.

I can't seem to find any detailed docs as to how this might work together.

2

There are 2 answers

0
skube On BEST ANSWER

I'm going to answer my own question. I could be wrong but it seems it's an easy process. Simply require the plugin (in this case, I want to use imagemin-jpeg-recompress plugin). Then specify the plugin to use within imagemin via the use property of imagemin. I believe this will override the bundled jpegtran optimizer that comes 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' 
      })]
    }))
});
2
fpapado On

In the new versions (3.x) of gulp-imagemin, the solution above doesn't work. The reason is that they changed how plugins are declared and configured to an array syntax and scoped arguments.

The API change is documented in Release 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 pass in an array of plugins you need to explicitly pass in every plugin you want, not just the ones you want to change options for."

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

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

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 on gulp-imagemin github issue tracker