Created
October 16, 2023 17:18
-
-
Save bryanjhv/4ab87c68d6bc31f027892d48da849400 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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