LoginSignup
3
0

More than 1 year has passed since last update.

npm-scripts で webp 画像を作成するデモ

Last updated at Posted at 2021-04-27

npm scripts で webp 画像を作成するデモです。

環境

$ node -v
v12.14.1

プロジェクトの作成とプロジェクトルートディレクトリへの移動

$ mkdir test-sharp && cd test-sharp

npm パッケージを新規でセットアップする

今回はオプション -y で質問を省略しています。

$ npm init -y

インストール

sharp-cliをインストールします。

$ npm i -D sharp-cli

package.json にコマンドを記述します。

package.json
{
  "scripts": {
    "sharp": "npm run sharp-webp & npm run sharp-png & npm run sharp-jpg",
    "sharp-webp": "sharp -i ./src/images/**/*.jpg ./src/images/**/*.png -f webp -o ./dist/images",
    "sharp-jpg": "sharp -i ./src/images/**/*.jpg -o ./dist/images",
    "sharp-png": "sharp -i ./src/images/**/*.png -o ./dist/images"
  }
}

簡単に解説すると、

  • "sharp" で下記の3つの scripts を順次処理する。

  • "sharp-webp:./src/images/ ディレクトリに保存された .jpg.png.webp にフォーマットして ./dist/images/ に保存する。

  • "sharp-jpg"./src/images/ ディレクトリに保存された .jpg 、を圧縮して ./dist/images/ に保存する。

  • "sharp-png"./src/images/ ディレクトリに保存された .png 、を圧縮して ./dist/images/ に保存する。

ということです。

なお、
* オプションの -q で PNG の圧縮率(0 - 9)を変えられます。(デフォルトは 9 です)
* オプションの -c で JPG の画質(1 - 99)を変えられます。(デフォルトは 80 です)

圧縮前の画像ディレクトリと書出し用の画像ディレクトリの作成

$ mkdir -p src/images & mkdir -p dist/images

ここまでのディレクトリ構成

.
├── dist
│   └── images
├── node_modules
├── package-lock.json
├── package.json
└── src
    └── images

圧縮前の画像を準備

src/images に圧縮したい画像を保存します。

npm scripts を実行する

$ npm run sharp

./dist/images/ に圧縮画像が書き出されます。

画像サイズの変化

圧縮率はデフォルトの 80 です。

圧縮前 圧縮後 圧縮後 WEBP
a.jpg 78KB 56KB 31KB
b.png 86KB 58KB 19KB
c.jpg 119KB 81KB 44KB

PICTURE タグを使って画像を切り替える

<picture>
  <source srcset="dist/images/test.webp" media="(min-width: 800px)">
  <img src="dist/images/test.jpg" alt="" />
</picture>

800px 以上では dist/images/test.webp が表示され、800px 未満では dist/images/test.jpg が表示されます。

参考

GitHub - vseventer/sharp-cli: CLI for sharp.
Node.jsのライブラリsharpの出力形式について | Simple is Beautiful.

3
0
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
3
0