Skip to content

Instantly share code, notes, and snippets.

@bryanjhv
Created October 16, 2023 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanjhv/4ab87c68d6bc31f027892d48da849400 to your computer and use it in GitHub Desktop.
Save bryanjhv/4ab87c68d6bc31f027892d48da849400 to your computer and use it in GitHub Desktop.
import { extname } from 'node:path'
import sharp, { FormatEnum } from 'sharp'
import type { Plugin } from 'vite'
function sharpPlugin(): Plugin {
return {
name: 'vite:sharp',
enforce: 'post',
apply: 'build',
async generateBundle(_, bundle) {
for (const asset of Object.values(bundle)) {
if (asset.type == 'chunk') continue
if (!/\.(jpe?g|png)$/i.test(asset.name!)) continue
const source = asset.source as Buffer
const ext = extname(asset.name!).slice(1).toLowerCase()
const result = await sharp(source)
.toFormat(ext as keyof FormatEnum)
.toBuffer()
if (result.byteLength >= source.byteLength) continue
asset.source = result
}
}
}
}
export default sharpPlugin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment