コンテンツにスキップ

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.

  • An Astro project using Markdown for content pages.
  1. Install both @astrojs/markdown-satteri and satteri:

    Terminal window
    npm install @astrojs/markdown-satteri satteri
  2. Create a Sätteri hast plugin that adds an icon if the link starts with http:

    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: "🔗",
    },
    ],
    });
    }
    },
    },
    });
  3. Configure the plugin in your astro.config.mjs file.

    Import satteri() and define it as the Markdown processor to add custom Sätteri plugins. Then, pass to hastPlugins an array containing your imported hastExternalLinks plugin.

    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],
    }),
    },
    });
貢献する コミュニティ スポンサー