【最新版】Gulp4で画像を一気に圧縮させてみた

Gulp
※当ブログの記事内にはプロモーションが含まれている場合があります。

こんにちは。panshokuです。

今回は、Gulp4を使って画像を一気に圧縮させようと思います。

Gulpを使わなくても、ブラウザ上で圧縮するようなサービスもあります。
とても便利で私もよく利用していましたが、頻繁に画像圧縮を繰り返していると、
サイトへのアップロード・ダウンロード・展開…の繰り返しが億劫になってしまい、
面倒くさがりの私は、自動化してしまおう!と今回の実装に踏み切りました。。

1. 前提

環境

  • Windows
  • WSL2 (Ubuntu) (Linux)

Windowsですが、 Linux のコマンドが使えるようにしています。

Macの方は、この記事と同じコマンドが使用できます が、Windowsでlinuxを入れていない方は、
コマンドを適宜変更しながら進めるようお願いします。

ホームディレクトリ

それぞれの環境のホームディレクトリです。

  • Windows + WSL2 : /mnt/c/Users/****
  • Mac : /Users/****
  • Windows : C:¥Users¥****

記述形式

  • ES Module (ES6)

※後述する、gulp-imageminのバージョンが v7.1.0 以降のため

2. 流れ

  1. Gulpをインストール
  2. gulp-imageminをインストール
  3. gulpfile.jsを記述
  4. 画像圧縮実行

3. Gulpインストール

ホームディレクトリに移動

コマンドプロンプトを開いて、書くコマンドを打ち込んでいきます。
念の為、ホームディレクトリに移動しておきます。
※私の環境でのコマンドなので、「前提」よりご自身の環境のホームディレクトリを使用してください。

$ cd /mnt/c/Users/watanabenozomi

Node.jsが入っているか確認

$ node -v
v14.15.1

14.15.1 のバージョンが入っています。

バージョンが表示されない場合、nodeが入っていないので、下記の公式サイトよりダウンロードして、手順にしたがってインストールします。

ダウンロードページには、「推奨版」と「最新版」のダウンロードリンクがありますが、 「推奨版」 をダウンロードすることをおすすめします。

https://nodejs.org/ja/

フォルダ作成

最終的に、gulpで画像を圧縮させたいので、その機能を動かすためのフォルダを作成します。

フォルダ名 : gulp_platform

$ mkdir gulp_platform

作成したフォルダに移動します。

$ cd gulp_platform

package.json作成

package.jsonファイル(設定ファイル)を生成します。

$ npm init -y
Wrote to /mnt/c/Users/****/gulp_platform/package.json:
{
  "name": "gulp_platform",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

作成されました。

Gulpをインストール

$ npm install -D gulp
...

+ gulp@4.0.2
added 327 packages from 226 contributors in 70.45s

8 packages are looking for funding
  run `npm fund` for details

作成されたか、確認

$ ls
node_modules       package.json
package-lock.json

OK

4. 画像圧縮機能を実装

Gulpがインストールできたので、画像を圧縮する機能を実装します。

ディレクトリ構成

下記のディレクトリ構成を使用します。

gulp_platform
 |_ node_modules
 |_ package.json
 |_ package-lock.json
 |_ gulpfile.js // 圧縮するコードを書く
 |_ dist
 |   |_ images // 圧縮後の画像が格納される
 |_ src
 |   |_ images // 圧縮したい画像を入れる

ES Moduleに対応させておく

下記のパッケージを最新で使用するには、ES Moduleの記述をする必要があるため、対応しておきます。

package.jsonにtypeを追加

下記の☆部分を追記します。※直前のカンマを忘れずに!

// package.json

{
  "name": "gulp_platform",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "gulp": "^4.0.2",
    "gulp-imagemin": "^8.0.0"
  },
  "type": "module" // -----------------☆
}

画像圧縮パッケージをインストール

$ npm i -D gulp-imagemin
...

+ gulp-imagemin@8.0.0
added 254 packages from 135 contributors in 91.842s

50 packages are looking for funding
  run `npm fund` for details

gulp-imagemin@7.1.0 以降のバージョンは、 ES Module形式 で記述する必要があります。今回は、 v8.0.0 なので、 ES Module で記述していきます。

gulpfile.jsを作成・編集

gulpfile.jsを作成します。

$ touch gulpfile.js

確認。

$ ls
gulpfile.js   package-lock.json
node_modules  package.json

gulpfile.jsが作成されています。OK。

gulpfile.jsを編集していきます。

import gulp from 'gulp';
import imagemin from 'gulp-imagemin';

// 画像圧縮タスク
const ImgImagemin = () => {
  return gulp
    .src("./src/images/**") // 圧縮処理を実行するディレクトリ
    .pipe(imagemin()) // 圧縮処理
    .pipe(gulp.dest("./dist/images")) // このディレクトリに圧縮した画像を出力
};

// 実行するタスクを記述
export const imgmin = (done) => {
  ImgImagemin(); // 画像圧縮タスクの実行
  done(); // 処理を終わらせる魔法のことば
}

// defaultがないとエラーになるので記述しておく
export default (done) => { done(); }

gulp4以前を使用していた人は、pipeが見慣れないかもしれませんが、gulp4からは、 gulp.task() は非推奨になったので注意です!

フォルダを作成

実行までに、画像のやりとりをするフォルダを用意します。

$ mkdir src
$ mkdir src/images
$ mkdir dist
$ mkdir dist/images

確認。

$ ls
dist          package-lock.json
gulpfile.js   package.json
node_modules  src

OK

画像圧縮処理実行!

まずは、 gulp_platform/src/images に圧縮したい画像を入れておきます。

src
  |_ images
  |    |_ order.png
  |    |_ soccer.png

それでは、実行してみます。

$ npx gulp imgmin
[23:01:42] Using gulpfile /mnt/c/Users/watanabenozomi/gulp_platform/gulpfile.js
[23:01:42] Starting 'imgmin'...
[23:01:42] Finished 'imgmin' after 26 ms
[23:02:03] gulp-imagemin: Minified 3 images (saved 174 kB - 19.3%)

下記のように出力されました

dist
  |_ images
  |    |_ order.png
  |    |_ soccer.png

画像サイズの確認をしてみます。

画像圧縮前

$ ls -lh src/images/
-rwxrwxrwx 1 root root 359K Mar 17 22:51 order.png
-rwxrwxrwx 1 root root 458K Mar 17 22:51 soccer.png

画像圧縮前

$ ls -lh dist/images/
-rwxrwxrwx 1 root root 291K Mar 17 22:51 order.png
-rwxrwxrwx 1 root root 382K Mar 17 22:51 soccer.png

ちょっとですが、圧縮されました(拍手)

以上お疲れさまでした!!!

5. もうちょっと圧縮したい…

pngはあまり圧縮されないようなので、追加で実装しました。
長くなったので、その記事はこちらへ。

— 準備中 —-

6. ES modules対応をしないとどうなるか…?

gulp-imageminをインストールしたときに、下記のエラーが出ます。
※バージョンが7.1.0以降のため

require() of ES modules is not supported.
require() of /******/node_modules/imagemin-mozjpeg/index.js from ****/gulpfile.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from ****/node_modules/imagemin-mozjpeg/package.json.

ES modulesの記述じゃないと、requireは使えないよ~~~。と言っています。なので、おとなしく、ES modulesを使うようにしました。
※当方、React・Vue使いなので、ES6のほうが好きという理由もあります…

7. 参考サイト

絶対つまずかないGulp 4入門 - インストールとSassを使うまでの手順 - ICS MEDIA
ウェブサイト制作には煩雑な処理を自動化する「タスクランナー」や「ビルドシステム」というツールがあります。この記事では、タスクランナー「Gulp.jsガルプ」の導入手順を解説します。導入は簡単で、本記事の手順では5分程度でセットアップできます...
gulp-imageminを使って画像を圧縮する【gulp4】
gulpを使って画像を自動で圧縮する方法について説明していきます。gulp-imageminを使えば大量の画像でも手軽に圧縮をすることができます。オンラインサービスや手動で画像の圧縮をして手間に感じている方はgulpでの画像圧縮が便利ですの...
404: This page could not be found

コメント

タイトルとURLをコピーしました