LoginSignup
4
2

More than 5 years have passed since last update.

flyで画像減色プラグインを書いてみる

Posted at

はじめに

flyのプラグインを適当に書いてみました。
flyってなんだよという方は
FlyでES6/7時代のJavaScriptビルドシステムとやらを体験してみた
Gruntやgulp等に続くタスク自動化ツール「Fly」の導入手順
などの分かりやすい記事があるので読んでみるとだいたい分かると思います。

公式のドキュメントにプラグインに関しての記述があります。(日本語版より英語版の方が詳しいので英語版をおすすめします)
あとyeomanでテンプレートも提供されています。

実際に作ったもの

pngquantを使って任意の画像を減色するプラグインを書いてみました。

index.js
const execFile = require('child_process').execFile;
const pngquant = require('pngquant-bin');
const imagemin = (options, cb) => {
  execFile(pngquant, ['-ext', '.png', options.color, options.src, '--force'], (err) => {
    cb(null);
  });
};

// プラグインの定義
// imageがflyfile側で呼び出すメソッド名になる
// optionsにはsrc, colorが渡される
module.exports = function () {
  this.image = (options) => {
    return this.defer(imagemin)(options);
  };
};
flyfile.js
export default function* () {
  yield this
    .image({
      src: 'img/test.png',
      color: 256
    })
}

感想

特に何も設定せずにES6で書けるのいいですね。
Fly.prototype.watchとか使えば任意のディレクトリを監視して画像が追加されたら減色とか出来そう?
今回はoptionに全て値を渡してしまったので、次はflyから提供されているメソッドをもう少し使って何か書きたいと思います。
あとimagemin関数にcbが渡されているのに気付かずfinish logが出力されずハマりました。
プラグインはまだ5,60ぐらいしかなさそうなので色々作るチャンスだと思います(・∀・)

4
2
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
4
2