vHeemstra / vite-plugin-imagemin

Vite plugin to compress/minify images with Imagemin
MIT License
19 stars 2 forks source link

`makeWebp` doesn't rename imports #18

Open not-nullptr opened 1 month ago

not-nullptr commented 1 month ago

right now, makeWebp generates the proper .webp files on build. however the actual site itself still uses the regular formats.

vHeemstra commented 1 month ago

That's correct, this plugin only handles the minification of the image files.

To have the server serve the WebP (or AVIF) version of the image instead, you can use a .htaccess script like mentioned in README.md.

not-nullptr commented 1 month ago

might be worth adding a few scripts which do it for various frameworks into the readme too, for people who are using SSR? here's one for sveltekit i wrote which runs after build:


import { readFileSync, writeFileSync } from "fs";

const hook = "const handler = sequence(";
const code = `(req, res, next) => {
        // if the url ends with .png, .jpg, .jpeg redirect to the same path but with .webp appended
        if (req.url.match(/\.(png|jpg|jpeg)$/)) {
                res.writeHead(301, {
                    Location: req.url + '.webp'
                });
                res.end();
            }
        next();
    },`;
const file = readFileSync("./build/handler.js").toString();
if (
    file.includes(
        "if the url ends with .png, .jpg, .jpeg redirect to the same path but with .webp appended",
    )
) {
    console.log("webp-hook.js already applied");
    process.exit(0);
}
const lines = file.split("\n");
const line = lines.findIndex((line) => line === hook);
// push string after line
lines.splice(line + 2, 0, code);
const newFile = lines.join("\n");
// write new file
writeFileSync("./build/handler.js", newFile);

const grayAnsi = "\x1b[90m";
const greenAnsi = "\x1b[32m";
const blueAnsi = "\x1b[34m";
const resetAnsi = "\x1b[0m";
console.log(
    `${grayAnsi}[${blueAnsi}webp-hook.js${grayAnsi}] ${greenAnsi}successfully applied webp hook into generated node server.`,
);
//  run ${resetAnsi}bun preview${greenAnsi} to run server.${resetAnsi}
console.log(
    `${grayAnsi}[${blueAnsi}webp-hook.js${grayAnsi}] ${greenAnsi}run ${resetAnsi}bun preview${greenAnsi} to begin the server.${resetAnsi}`,
);
vHeemstra commented 1 month ago

Implementations of handling returning PNG/JPG or their WebP/AVIF versions is a bit out of scope for this package. But if you make a Gist with an example/howto, I will link it in the README.

Because the client might not support WebP/AVIF, this is the reason to always keep the original PNG/JPG and not rename the imported filepath to allow the server to deliver the best content based on the request Accept header.

I am not that familiar with Sveltkit or SSR in general, but keep in mind that the server should check this request Accept header to see if the client supports the format before returning an alternative version.