441 字
2 分钟
Fuwari:如何让外部链接自动在新标签页打开

为什么需要这个优化?#

Fuwari 默认对 Markdown 中的链接处理较为简单,点击外部链接时会直接在当前页面跳转。这对于读者来说并不友好:当他们想看一眼参考资料时,原本的阅读进度就被迫中断了。

为了解决这个问题,我们可以利用 rehype-external-links 插件,它能自动识别外部链接并为其注入 target="_blank" 属性,从而让外部链接自动在新标签页打开。

rehypejs
/
rehype-external-links
Waiting for api.github.com...
00K
0K
0K
Waiting...

安装插件#

进入博客根目录,使用包管理器安装插件:

Terminal window
pnpm add rehype-external-links

配置Astro 配置文件#

安装完成后,我们需要在 astro.config.mjs 中启用它。 在博客根目录编辑 astro.config.mjs 文件,在文件顶部引入插件:

astro.config.mjs
import rehypeComponents from "rehype-components";
import rehypeExternalLinks from "rehype-external-links";
import rehypeKatex from "rehype-katex";

找到 markdown 配置部分的 rehypePlugins 数组,添加 rehypeExternalLinks 配置:

astro.config.mjs
markdown: {
//... 其他配置
rehypePlugins: [
rehypeKatex,
[
rehypeExternalLinks,
{
target: "_blank",
rel: ["nofollow", "noopener", "noreferrer"],
},
],
rehypeSlug,
//... 其他插件
]
//... 其他配置
}

参数说明#

  • target: "_blank" :强制链接在新标签页打开。

  • rel: ['nofollow', 'noopener', 'noreferrer'] :添加安全属性。

    • nofollow :告诉搜索引擎不要追踪此链接,保护站点权重。
    • noopener & noreferrer :阻断新页面对原页面的控制权限,防范恶意脚本攻击。

进阶技巧#

该插件也可以给外部链接加一个小图标(比如 ),你可以添加一个 content 属性:

astro.config.mjs
rehypeExternalLinks,
{
target: "_blank",
content: { type: "text", value: "↗" }
},

这样,所有的外部链接后面都会自动跟一个箭头符号,清晰地提示用户 这是一个外部跳转

对比测试#

Fuwari:如何让外部链接自动在新标签页打开
https://www.smaritron.top/posts/ext-links-blank/
作者
Smaritron
发布于
2026-02-13
许可协议
CC BY-NC-SA 4.0