UNPKG

vite-plugin-single-image-format

Version:

vite-plugin-single-image-format is a Vite/Rollup plugin that converts every raster asset in your build to a single output format – webp, png or avif. It can optionally re‑compress images that are already in the target format and automatically rewrites all

32 lines (31 loc) 1.58 kB
import c from "sharp"; function B(l = {}) { const { format: n = "webp", reencode: u = !1, webp: m = {}, png: g = {}, avif: w = {} } = l, b = { quality: 88, alphaQuality: 90, smartSubsample: !0, ...m }, d = { quality: 80, compressionLevel: 9, palette: !0, adaptiveFiltering: !0, ...g }, y = { quality: 60, lossless: !1, speed: 5, ...w }, p = /\.(png|jpe?g|webp|gif|avif|heif|heic|tiff?|bmp|jp2)$/i, $ = [".html", ".css", ".js", ".mjs", ".ts"]; return { name: "vite-plugin-single-image-format", apply: "build", enforce: "post", async generateBundle(v, o) { const r = /* @__PURE__ */ new Map(); for (const [e, t] of Object.entries(o)) { if (t.type !== "asset" || !p.test(e)) continue; const s = e.toLowerCase().endsWith(`.${n}`); if (s && !u) continue; const i = (t.source, Buffer.from(t.source)), a = n === "webp" ? await c(i).webp(b).toBuffer() : n === "png" ? await c(i).png(d).toBuffer() : await c(i).avif(y).toBuffer(); if (s) { t.source = a; continue; } const f = e.replace(p, `.${n}`); o[f] || (this.emitFile({ type: "asset", fileName: f, source: a }), r.set(e, f), delete o[e]); } if (r.size !== 0) for (const e of Object.values(o)) { if (e.type !== "asset" || !$.some((s) => e.fileName.endsWith(s))) continue; let t = e.source.toString(); for (const [s, i] of r) { const a = s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); t = t.replace(new RegExp(`([./]*)${a}`, "g"), (f, h) => `${h}${i}`); } e.source = t; } } }; } export { B as default };