feat: add rehypePictureWebp plugin for optimized image handling

This commit is contained in:
2026-03-17 16:46:32 +09:00
parent d91acce2f9
commit 8600a088a2
2 changed files with 45 additions and 2 deletions
+4 -2
View File
@@ -4,7 +4,8 @@ import mdx from "@astrojs/mdx";
import tailwindcss from "@tailwindcss/vite"; import tailwindcss from "@tailwindcss/vite";
import icon from "astro-icon"; import icon from "astro-icon";
import remarkReadingTime from "remark-reading-time"; import remarkReadingTime from "remark-reading-time";
import { remarkR2Images } from './src/plugins/remark-r2-images.mjs'; import { remarkR2Images } from "./src/plugins/remark-r2-images.mjs";
import { rehypePictureWebp } from "./src/plugins/rehype-picture-webp.mjs";
export default defineConfig({ export default defineConfig({
site: "https://balodeplao.com/", site: "https://balodeplao.com/",
@@ -18,8 +19,9 @@ export default defineConfig({
file.data.readingTime.minutes; file.data.readingTime.minutes;
}; };
}, },
remarkR2Images remarkR2Images,
], ],
rehypePlugins: [rehypePictureWebp],
}, },
i18n: { i18n: {
defaultLocale: "vi", defaultLocale: "vi",
+41
View File
@@ -0,0 +1,41 @@
import { visit } from "unist-util-visit";
export function rehypePictureWebp() {
return (tree) => {
visit(tree, "element", (node, index, parent) => {
if (node.tagName !== "img") return;
if (!parent || index == null) return;
const src = node.properties?.src || "";
// Chỉ xử lý ảnh từ R2
if (!src.includes("media.balodeplao.com")) return;
if (!/\.(jpe?g|png)$/i.test(src)) return;
/* const webpSrc = src.replace(/\.(jpe?g|png)$/i, ".webp"); */
// Wrap <img> thành <picture> với WebP source + fallback
parent.children[index] = {
type: "element",
tagName: "picture",
properties: {},
children: [
/* {
type: "element",
tagName: "source",
properties: { type: "image/webp", srcSet: webpSrc },
children: [],
}, */
{
...node,
properties: {
...node.properties,
loading: "lazy",
decoding: "async",
},
},
],
};
});
};
}