Add icons to external links
このコンテンツはまだ日本語訳がありません。
Using a hast plugin, you can identify and modify links in your Markdown files that point to external sites. This example adds an icon to the end of each external link, so that visitors will know they are leaving your site.
Prerequisites
Section titled “Prerequisites”- An Astro project using Markdown for content pages.
Recipe
Section titled “Recipe”-
Install both
@astrojs/markdown-satteriandsatteri:Terminal window npm install @astrojs/markdown-satteri satteriTerminal window pnpm add @astrojs/markdown-satteri satteriTerminal window yarn add @astrojs/markdown-satteri satteri -
Create a Sätteri
hastplugin that adds an icon if the link starts withhttp:src/hast/hast-external-links.ts import { defineHastPlugin } from 'satteri';export const hastExternalLinks = defineHastPlugin({name: "hast-external-links",element: {filter: ["a"],visit(node, context) {if (node.properties.href?.startsWith("http")) {context.appendChild(node, {type: "element",tagName: "span",properties: { ariaHidden: "true" },children: [{type: "text",value: "🔗",},],});}},},}); -
Configure the plugin in your
astro.config.mjsfile.Import
satteri()and define it as the Markdown processor to add custom Sätteri plugins. Then, pass tohastPluginsan array containing your importedhastExternalLinksplugin.astro.config.mjs import { satteri } from '@astrojs/markdown-satteri';import { defineConfig } from 'astro/config';import { hastExternalLinks } from './src/hast/hast-external-links';export default defineConfig({markdown: {processor: satteri({hastPlugins: [hastExternalLinks],}),},});
-
Install both the
rehype-external-linksplugin and@astrojs/markdown-remark.Terminal window npm install rehype-external-links @astrojs/markdown-remarkTerminal window pnpm add rehype-external-links @astrojs/markdown-remarkTerminal window yarn add rehype-external-links @astrojs/markdown-remark -
Configure the plugin in your
astro.config.mjsfile.Import
unified()and define it as the Markdown processor to support remark plugins. Then, pass torehypePluginsan array containing your importedrehypeExternalLinksplugin and an options object with acontentproperty. Set this property’stypetotextif you want to add plain text to the end of the link. To add HTML to the end of the link instead, set the propertytypetoraw.astro.config.mjs import { unified } from '@astrojs/markdown-remark';import { defineConfig } from 'astro/config';import rehypeExternalLinks from 'rehype-external-links';export default defineConfig({markdown: {processor: unified({rehypePlugins: [[rehypeExternalLinks,{content: { type: 'text', value: ' 🔗' }}],]}),},});