8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

gulp-libsquoosh を使って webp/png/jpeg から複数のフォーマットに変換出力する

8
Posted at

gulp で画像最適化するのに gulp-imageminimagemin-pngquantimagemin-mozjpeggulp-webp を使ってたんですが、下記の理由から Squoosh に乗り換えることにしました。

  • ひとつのツールにまとめたい
  • 将来的に他のフォーマットに対応しやすそう
  • webのツールを使って他のメンバーとパラメーター値を共有しやすい

3つ目はこちらのサイトです。

パラメーター名の大文字小文字とか微妙な違いはありますが、ソースコードから探し出せます。

複数のフォーマットに出力したい

webp がほぼ全てのブラウザでサポートされるようになり、png + webp という感じに二種類用意することが増えてきました。

今回紹介する gulp-libsquoosh を使うと複数フォーマットの出力が簡単にできるのも大きなポイントです。

下記のサイトを参考にさせていただきました。

gulpfile.js

gulpfile.js
const path = require('path');
const gulp = require('gulp');
const squoosh = require('gulp-libsquoosh');

gulp.task('image', () => {
  return gulp
  .src('src/image/*.{png,jpg,avif}')
  .pipe(
    squoosh((args) => {
      // 拡張子を抽出
      const extname = path.extname(args.path);

      // png、jpg 以外(ここでは avif)用のデフォルト設定
      let options = {
        encodeOptions: squoosh.DefaultEncodeOptions[extname],
      };

      // png形式は png、webp の両方を出力する
      if (extname === '.png') {
        options = {
          encodeOptions: {
            oxipng: {
              quality: 80,
            },
            webp: {
              // ロスレス指定
              // 画像によっては lossless:false して quality 指定のほうが良いかも
              lossless: true,
            },
          },
        };
      }
      // jpeg形式は jpg、webp の両方を出力する
      if (extname === '.jpg') {
        options = {
          encodeOptions: {
            mozjpeg: {
              quality: 90,
            },
            webp: {
              quality: 80,
            },
          },
        };
      }
      // それ以外はデフォルト設定のまま
      return options;
    }),
  )
  .pipe(gulp.dest('src/image/optimize'));
});

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?