6
7

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 5 years have passed since last update.

npm-scripts:imageminを導入してみた

Last updated at Posted at 2019-05-10

前提

  • Windows環境
  • フロントエンド初学者
  • Node.js(v8.11.2)とnpm(v6.9.0)導入済
  • gulpでimagemin使ってた
  • タスクランナーをnpm-scriptsに乗り換えたかった

早速やってみる

必要なパッケージをまとめてインストール

npm install --save-dev imagemin imagemin-keep-folder imagemin-mozjpeg imagemin-pngquant imagemin-gifsicle imagemin-svgo onchange
package.json

{
  "name": "sample-npm-scripts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "npm run imagemin:watch",
    "imagemin": "node index.js",
    "imagemin:watch": "onchange \"src/images\" -- npm run imagemin"
  }, //Win環境ではエスケープした上でダブルクォーテーションでパスを括る
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "cpx": "^1.5.0",
    "imagemin": "^6.1.0",
    "imagemin-gifsicle": "^6.0.1",
    "imagemin-keep-folder": "^5.3.2",
    "imagemin-mozjpeg": "^8.0.0",
    "imagemin-pngquant": "^7.0.0",
    "imagemin-svgo": "^7.0.0",
    "npm-run-all": "^4.1.5",
    "onchange": "^5.2.0",
    "rimraf": "^2.6.3",
    "watch": "^1.0.2"
  }
}
index.js

const imagemin = require('imagemin-keep-folder');
const imageminMozjpeg = require('imagemin-mozjpeg');
const imageminPngquant = require('imagemin-pngquant');
const imageminGifsicle = require('imagemin-gifsicle');
const imageminSvgo = require('imagemin-svgo');

imagemin(['src/images/**/*.{jpg,png,gif,svg}'], {
  plugins: [
    imageminMozjpeg({ quality: 80 }),
    imageminPngquant({ quality: [0.65, 0.8] }), //'65-80'←この書き方だとエラー出た
    imageminGifsicle(),
    imageminSvgo()
  ],
  replaceOutputDir: output => {
    return output.replace(/images\//, './dist/images/')
  }
}).then(() => {
  console.log('Images optimized');
});

あとは実行

npm start
または
npm run imagemin

感想

エラーが何度か出て一発では動かなかったのですが、やりたかったことができました。
pngquantの画質設定を配列かつ小数点で指定するのとかは情報がすぐ出てこなかった。
https://www.npmjs.com/package/imagemin-pngquant
でもこれでディレクトリ構造を維持したまま、画像が追加されたら自動でdist以下に圧縮保存されます。

参考サイト
https://qiita.com/minase_tetsuya/items/986feac7150ed74e13d8
https://techblog.lclco.com/entry/2018/08/31/180000

6
7
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
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?