为外部链接添加图标
通过使用 rehype 插件,你可以识别并修改 Markdown 文件中指向外部网站的链接。本示例在每个外部链接的末尾添加图标,以便访问者知道他们即将离开你的网站。
先决条件
标题为“先决条件”的部分- 一个使用 Markdown 作为内容页面的 Astro 项目。
-
安装
rehype-external-links
插件。终端窗口 npm install rehype-external-links终端窗口 pnpm add rehype-external-links终端窗口 yarn add rehype-external-links -
将插件导入到你的
astro.config.mjs
文件中。将
rehypeExternalLinks
连同一个包含 content 属性的选项对象一起传递给rehypePlugins
数组。如果你想在链接末尾添加纯文本,请将此属性的type
设置为text
。如果想在链接末尾添加 HTML,请将属性type
设置为raw
。// ...import rehypeExternalLinks from 'rehype-external-links';export default defineConfig({// ...markdown: {rehypePlugins: [[rehypeExternalLinks,{content: { type: 'text', value: ' 🔗' }}],]},});content
属性的值不会在无障碍树中表示。因此,最好在周围的内容中明确指出该链接是外部链接,而不仅仅依赖于图标。