diff --git a/astro.config.mjs b/astro.config.mjs index ce0901844..f3e7b3ea2 100644 --- a/astro.config.mjs +++ b/astro.config.mjs @@ -14,7 +14,8 @@ import remarkMath from "remark-math"; import remarkSectionize from "remark-sectionize"; import { AdmonitionComponent } from "./src/plugins/rehype-component-admonition.mjs"; import { GithubCardComponent } from "./src/plugins/rehype-component-github-card.mjs"; -import { rehypeImageFallback } from "./src/plugins/rehype-image-fallback.mjs"; +import rehypeImageFallback from "./src/plugins/rehype-image-fallback.mjs"; +import { siteConfig, imageFallbackConfig } from './src/config.ts'; import { parseDirectiveNode } from "./src/plugins/remark-directive-rehype.js"; import { remarkExcerpt } from "./src/plugins/remark-excerpt.js"; import { remarkReadingTime } from "./src/plugins/remark-reading-time.mjs"; @@ -66,7 +67,7 @@ export default defineConfig({ rehypePlugins: [ rehypeKatex, rehypeSlug, - rehypeImageFallback, + [rehypeImageFallback, imageFallbackConfig], [ rehypeComponents, { diff --git a/src/plugins/rehype-image-fallback.mjs b/src/plugins/rehype-image-fallback.mjs index e770d073d..f685e1855 100644 --- a/src/plugins/rehype-image-fallback.mjs +++ b/src/plugins/rehype-image-fallback.mjs @@ -1,16 +1,21 @@ import { visit } from 'unist-util-visit'; -import { imageFallbackConfig } from '../config.ts'; -export default function rehypeImageFallback() { +export default function rehypeImageFallback(options = {}) { + const { + enable = true, + originalDomain = 'r2.afo.im', + fallbackDomain = 'pub-d433ca7edaa74994b3d7c40a7fd7d9ac.r2.dev' + } = options; + return (tree) => { visit(tree, 'element', (node) => { if (node.tagName === 'img' && node.properties && node.properties.src) { const src = node.properties.src; // 检查是否启用回退功能并且是来自指定域名的图片 - if (imageFallbackConfig.enable && typeof src === 'string' && src.includes(imageFallbackConfig.originalDomain)) { + if (enable && typeof src === 'string' && src.includes(originalDomain)) { // 生成备用 URL - const fallbackSrc = src.replace(imageFallbackConfig.originalDomain, imageFallbackConfig.fallbackDomain); + const fallbackSrc = src.replace(originalDomain, fallbackDomain); // 添加 onerror 属性 node.properties.onerror = `this.onerror=null; this.src='${fallbackSrc}';`;