diff --git a/astro.config.mjs b/astro.config.mjs index aadfeee..ca221f0 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -4,7 +4,8 @@ import mdx from "@astrojs/mdx"; import tailwindcss from "@tailwindcss/vite"; import icon from "astro-icon"; 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({ site: "https://balodeplao.com/", @@ -18,8 +19,9 @@ export default defineConfig({ file.data.readingTime.minutes; }; }, - remarkR2Images + remarkR2Images, ], + rehypePlugins: [rehypePictureWebp], }, i18n: { defaultLocale: "vi", diff --git a/src/plugins/rehype-picture-webp.mjs b/src/plugins/rehype-picture-webp.mjs new file mode 100644 index 0000000..c23442c --- /dev/null +++ b/src/plugins/rehype-picture-webp.mjs @@ -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 thành 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", + }, + }, + ], + }; + }); + }; +}