UNPKG

@firstfleet/imagemin-brunch

Version:

Fork of stawberri/imagemin-brunch. Simple image minification for brunch

124 lines (101 loc) 3.59 kB
import fs from "node:fs"; import imagemin from "imagemin"; import loggy from "loggy"; import plur from "plur"; import prettyBytes from "pretty-bytes"; const imageminPattern = /\.(gif|jpg|jpeg|jpe|jif|jfif|jfi|png|svg|svgz)$/; const imageminPlugins = { "imagemin-gifsicle": true, "imagemin-jpegtran": true, "imagemin-optipng": true, "imagemin-svgo": true, }; export default class ImageminBrunch { constructor(config) { this.init(config); } async init(config) { this.config = config.plugins.imagemin || {}; if (new Object(this.config.plugins) !== this.config.plugins) { this.config.plugins = {}; } this.config.plugins = Object.assign( {}, imageminPlugins, this.config.plugins ); this.plugins = []; let pluginLoads = 0; for (let plugin in this.config.plugins) { let options = this.config.plugins[plugin]; if (!options) { continue; } else { pluginLoads++; } try { const imageminPlugin = await import(plugin); if (new Object(options) === options) { this.plugins.push(imageminPlugin.default(options)); } else { this.plugins.push(imageminPlugin.default()); } } catch (err) { loggy.warn(`Loading of ${plugin} failed due to`, err.message); } } if (!this.plugins.length && pluginLoads) { throw new Error("No imagemin plugins loaded"); } if (!("pattern" in this.config)) { this.config.pattern = imageminPattern; } this.config.pattern = new RegExp(this.config.pattern); } onCompile(err, assets) { let startTime = Date.now(); let promises = []; let oldBytes = 0; let newBytes = 0; for (let asset of assets) { if (!this.config.pattern.test(asset.destinationPath)) { continue; } promises.push( new Promise((res, rej) => { let data = Buffer.from(asset.compiled); oldBytes += data.length; imagemin .buffer(data, { plugins: this.plugins }) .then((buffer) => { newBytes += buffer.length; fs.writeFile( asset.destinationPath, buffer, (err) => { if (err) rej(err); else res(); } ); }); }) ); } Promise.all(promises) .then(() => { let elapsed = ((Date.now() - startTime) / 1000).toFixed(1); let saved = prettyBytes(oldBytes - newBytes); loggy.info( `minified ${promises.length} ${plur( "image", promises.length )} to save ${saved} in ${elapsed} sec` ); }) .catch((err) => { loggy.error("Image minification failed due to", err.message); }); } optimize() {} } Object.setPrototypeOf(ImageminBrunch.prototype, { brunchPlugin: true });