EmDashのPortable Textで外部リンクを自動判別し、アイコン・target="_blank"・rel属性を付与する方法
EmDashのPortable Textレンダリング(mark.link)をカスタマイズし、本文やテーブル内の外部リンクだけにtarget="_blank"・rel="noopener noreferrer"と外部リンクアイコンをSSRで自動付与する実装方法を解説します。
目次
技術ブログでは公式ドキュメントや参考サイトへリンクを貼る機会が多くあります。しかし、デフォルトの <a> タグのままだと「内部リンクか外部リンクか見た目で分からない」「同じタブで開いてしまい元記事に戻りづらい」といった小さなストレスが生まれます。
そこでこのサイト(EmDash)では、記事本文や固定ページの PortableText をカスタマイズし、外部サイトへのリンクだけに target="_blank"・rel="noopener noreferrer" と外部リンクアイコンをサーバーサイドで自動付与する仕組みを導入しました。
なぜクライアントJSではなく PortableText の mark で処理するのか
ページ読み込み後に JavaScript で document.querySelectorAll('a') を走らせて属性を後付けする方法もありますが、Portable Text のレンダリング段階で処理するほうが以下の点で優れています。
- レイアウトシフトやチラつきが起きない:アイコンも含めて最初から HTML として出力されるため、表示後のガタつきがありません。
- JS不要・クローラーにも確実:初期 HTML の時点で
rel="noopener noreferrer"が出力されます。 - EmDash の仕組みと相性が良い:
emdash/uiの<PortableText>は内部でastro-portabletextをラップしており、ユーザー側のcomponents.mark.linkを渡すだけでリンク描画を上書きできます。
実装手順
1. 外部リンク判定コンポーネント(LinkMark.astro)を作成する
まず src/components/LinkMark.astro を作成し、リンク先が外部ドメインかどうかを判定します。相対パス(/posts/...)やページ内アンカー(#...)、mailto:、および自サイトドメイン宛の絶対URLは内部リンクとしてそのまま出力します。
---
import type { MarkProps } from "astro-portabletext/types";
export type Props = MarkProps<{ href?: string }>;
const { node, index: _index, isInline: _isInline, ...attrs } = Astro.props;
const href = node?.markDef?.href ?? "";
function isExternalHref(rawHref: string, siteHostname: string): boolean {
if (!rawHref || !/^(https?:)?\/\//i.test(rawHref)) return false;
try {
const url = new URL(rawHref.startsWith("//") ? `https:${rawHref}` : rawHref);
const host = url.hostname.toLowerCase();
const current = siteHostname.toLowerCase();
return host !== current && host !== "weblabo.net" && host !== "www.weblabo.net";
} catch {
return false;
}
}
const isExternal = isExternalHref(href, Astro.url.hostname);
---
{
isExternal ? (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
class="external-link"
{...attrs}
>
<slot />
<svg
class="external-link__icon"
viewBox="0 0 24 24"
width="12"
height="12"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M15 3h6v6" />
<path d="M10 14 21 3" />
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
</svg>
</a>
) : (
<a href={href} {...attrs}>
<slot />
</a>
)
}
2. 記事・固定ページ・テーブルの PortableText に組み込む
作成した LinkMark を、記事詳細(src/pages/posts/[slug].astro)、固定ページ(src/pages/pages/[slug].astro)、およびテーブルブロック内のセルを描画する src/components/TableBlock.astro の <PortableText> に渡します。
<PortableText
value={post.data.content}
components={{
type: { code: CodeBlock, file: FileBlock, callout: CalloutBlock, table: TableBlock },
mark: { link: LinkMark },
}}
/>
3. 外部リンクアイコンのスタイルを整える
アイコンのサイズは em 単位にしておくと、見出しや本文・テーブル内などフォントサイズが変わる場所でも自然に馴染みます。
.prose .external-link__icon {
display: inline-block;
width: 0.78em;
height: 0.78em;
margin-left: 0.22em;
vertical-align: -0.06em;
opacity: 0.72;
transition: opacity 0.15s ease, transform 0.15s ease;
}
.prose a.external-link:hover .external-link__icon {
opacity: 1;
transform: translate(1px, -1px);
}
実際の表示とまとめ
たとえば Astro 公式ドキュメント や EmDash 公式サイト のような外部URLを本文に貼ると、末尾にアイコンが付き別タブで開くようになります。一方で、サイト内の別記事へのリンクは従来どおり同一タブでスムーズに遷移します。


