跳至内容
返回

在 Astro 项目中使用自定义 Remark 插件

发布于:  at  05:00 下午
阅读量: 0 文档卡片经过转换节点,变成彩色提示框和按钮组件。

本文介绍如何在全新的 Astro 项目中使用两个自定义 Remark 插件——remark-admonitions(提示框)和 remark-button(按钮),让 Markdown 内容支持丰富的自定义组件。

当然我也知道网上应该有不少开箱即用的插件,但我还是选择了这个方式。

效果预览

在正式安装之前,先来看看这两个插件能实现什么效果。

提示框(Admonitions)

五种提示框分别适用于不同场景:

这是一个普通的注意提示框,用于补充说明。

这是一个友好的提示信息,可以分享小技巧。

这是一个信息提示框,用于提供额外信息。

这是一个警告提示框,用于提醒用户注意。

这是一个危险警告,用于提醒用户谨慎操作。

按钮(Button)

以下是各种按钮变体:

小号主要按钮

中号成功按钮

大号危险按钮

警告按钮

自定义紫色圆角按钮

插件简介

这两个插件基于 remark-directive 构建,利用 Markdown 的 ::: 指令语法在文章中插入自定义 UI 组件。

前置依赖

在开始之前,确保你的项目满足以下条件:

需要安装的 npm 包:

包名用途
remark-directive解析 Markdown 中的 ::: 指令语法
unist-util-visit遍历和操作 AST 节点
hastscript以声明式方式创建 hast(HTML AST)节点
pnpm add remark-directive unist-util-visit hastscript

第一步:创建插件文件

在项目根目录下创建 plugins/ 目录,并将以下两个文件放入其中。

remark-admonitions.ts

import { visit } from "unist-util-visit";
import { h } from "hastscript";

const admonitions = ["note", "tip", "info", "warning", "danger"];

export default function remarkAdmonitions() {
  return tree => {
    visit(tree, node => {
      if (
        node.type === "containerDirective" ||
        node.type === "leafDirective" ||
        node.type === "textDirective"
      ) {
        if (admonitions.includes(node.name)) {
          const data = node.data || (node.data = {});
          const hast = h("div", node.attributes || {});

          if (node.children && node.children.length > 0) {
            const firstChild = node.children[0];
            if (firstChild.type === "paragraph") {
              const firstChildData = firstChild.data || (firstChild.data = {});
              const existingClass =
                (firstChildData.hProperties?.className as string[]) || [];
              firstChildData.hProperties = {
                ...firstChildData.hProperties,
                className: ["admonition-title", ...existingClass],
              };
            }
          }

          data.hName = hast.tagName;
          data.hProperties = {
            ...hast.properties,
            className: [
              node.name,
              ...((hast.properties?.className as string[]) || []),
            ],
          };
        }
      }
    });
  };
}

remark-button.ts

import { h } from "hastscript";
import type { Root } from "mdast";
import { visit } from "unist-util-visit";

const PRESET_SIZES = ["xs", "sm", "md", "lg", "xl"];
const PRESET_COLORS = [
  "primary",
  "secondary",
  "success",
  "danger",
  "warning",
  "info",
  "light",
  "dark",
  "pink",
  "purple",
  "indigo",
  "teal",
  "cyan",
  "orange",
];
const PRESET_TEXT_COLORS = ["white", "black", "gray", "light", "dark"];

export default function remarkButton() {
  return (tree: Root) => {
    visit(tree, node => {
      if (
        node.type !== "containerDirective" &&
        node.type !== "leafDirective" &&
        node.type !== "textDirective"
      ) {
        return;
      }

      if (node.name !== "button") return;

      const data = node.data || (node.data = {});
      const {
        color,
        textColor,
        size,
        padding,
        borderRadius,
        class: className,
        target,
        ...linkAttributes
      } = node.attributes ?? {};

      const hast = h("a", {
        ...linkAttributes,
        ...(className ? { class: className } : {}),
      });
      const classNames = [
        "custom-button",
        ...((hast.properties?.className as string[]) || []),
      ];
      const inlineStyles: string[] = [];

      if (size) {
        if (PRESET_SIZES.includes(size)) {
          classNames.push(`button-${size}`);
        } else {
          inlineStyles.push(`--button-font-size: ${size}`);
        }
      }

      if (color) {
        if (PRESET_COLORS.includes(color)) {
          classNames.push(`button-${color}`);
        } else {
          classNames.push("button-custom-color");
          inlineStyles.push(`--button-color: ${color}`);
        }
      }

      if (textColor) {
        if (PRESET_TEXT_COLORS.includes(textColor)) {
          classNames.push(`button-text-${textColor}`);
        } else {
          inlineStyles.push(`--button-contrast: ${textColor}`);
        }
      }

      if (padding) inlineStyles.push(`--button-padding: ${padding}`);
      if (borderRadius) {
        inlineStyles.push(`--button-radius: ${borderRadius}`);
      }

      const properties: Record<string, string | string[]> = {
        ...hast.properties,
        className: classNames,
        target: target || "_blank",
        rel: "noopener noreferrer nofollow",
      };

      if (inlineStyles.length > 0) {
        properties.style = inlineStyles.join("; ");
      }

      data.hName = "a";
      data.hProperties = properties;
    });
  };
}

第二步:配置 Astro

编辑 astro.config.ts,在 markdown.remarkPlugins 中注册这两个插件:

import { defineConfig } from "astro/config";
import remarkDirective from "remark-directive";
import remarkAdmonitions from "./plugins/remark-admonitions";
import remarkButton from "./plugins/remark-button";

export default defineConfig({
  markdown: {
    remarkPlugins: [
      remarkDirective, // 必须在自定义插件之前注册
      remarkAdmonitions,
      remarkButton,
    ],
  },
});

remarkDirective 必须排在 remarkAdmonitions 和 remarkButton 之前。因为 remark-directive 负责解析 ::: 语法生成 directive 节点,自定义插件再将这些节点转换为 HTML。如果顺序错误,自定义插件收不到 directive 节点,所有 ::: 区块都不会被渲染。

第三步:添加 CSS 样式

提示框样式

在你的全局 CSS 文件(如 src/styles/global.css)中添加:

/* 提示框基础样式 */
.prose .note,
.prose .tip,
.prose .info,
.prose .warning,
.prose .danger {
  @apply my-4 rounded-lg border-l-4 p-4;
}

/* 提示框标题 */
.prose .note .admonition-title,
.prose .tip .admonition-title,
.prose .info .admonition-title,
.prose .warning .admonition-title,
.prose .danger .admonition-title {
  @apply mb-2 text-lg font-bold;
}

/* 各类型配色 */
.prose .note {
  @apply border-blue-500 bg-blue-50 text-blue-900;
}

.prose .tip {
  @apply border-green-500 bg-green-50 text-green-900;
}

.prose .info {
  @apply border-cyan-500 bg-cyan-50 text-cyan-900;
}

.prose .warning {
  @apply border-yellow-500 bg-yellow-50 text-yellow-900;
}

.prose .danger {
  @apply border-red-500 bg-red-50 text-red-900;
}

/* 暗色模式适配 */
html[data-theme="dark"] .prose .note {
  @apply border-blue-400 bg-blue-950/50 text-blue-100;
}

html[data-theme="dark"] .prose .tip {
  @apply border-green-400 bg-green-950/50 text-green-100;
}

html[data-theme="dark"] .prose .info {
  @apply border-cyan-400 bg-cyan-950/50 text-cyan-100;
}

html[data-theme="dark"] .prose .warning {
  @apply border-yellow-400 bg-yellow-950/50 text-yellow-100;
}

html[data-theme="dark"] .prose .danger {
  @apply border-red-400 bg-red-950/50 text-red-100;
}

按钮样式

按钮样式通过一组 CSS 变量统一控制填充、边框、阴影、尺寸与文字对比度。这样预设变体、主题切换和自定义参数都使用同一套设计语言,同时保留站点原有的等宽字体与强调色。

/* ===== Markdown buttons (remark-button) ===== */
:root,
html[data-theme="light"] {
  --button-default-contrast: #fff;
}

html[data-theme="dark"] {
  --button-default-contrast: var(--background);
}

.custom-button {
  --button-color: var(--accent);
  --button-contrast: var(--button-default-contrast);
  --button-fill: var(--button-color);
  --button-fill-hover: color-mix(
    in srgb,
    var(--button-color) 88%,
    var(--foreground)
  );
  --button-border: var(--button-color);
  --button-padding: 0.55rem 0.95rem;
  --button-radius: 0.375rem;
  --button-font-size: 0.875rem;
  --button-gap: 0.65rem;
  --button-shadow: 3px;

  display: inline-flex;
  width: fit-content;
  max-width: 100%;
  align-items: center;
  justify-content: center;
  gap: var(--button-gap);
  margin-block: 0.75rem;
  padding: var(--button-padding);
  border: 1px solid var(--button-border);
  border-radius: var(--button-radius);
  background-color: var(--button-fill);
  box-shadow: var(--button-shadow) var(--button-shadow) 0
    color-mix(in srgb, var(--button-color) 22%, transparent);
  color: var(--button-contrast);
  font-size: var(--button-font-size);
  font-weight: 600;
  line-height: 1.35;
  letter-spacing: 0.01em;
  text-align: start;
  text-decoration: none;
  vertical-align: middle;
  transition:
    background-color 160ms ease,
    box-shadow 160ms ease,
    color 160ms ease,
    transform 160ms ease;
}

.custom-button::after {
  content: "↗";
  flex: none;
  font-size: 1.05em;
  font-weight: 400;
  line-height: 1;
  opacity: 0.82;
  transition: transform 160ms ease;
}

.custom-button[target="_self"]::after {
  content: "→";
}

.custom-button > p {
  margin: 0;
}

.custom-button:hover {
  background-color: var(--button-fill-hover);
  box-shadow: 1px 1px 0 color-mix(in srgb, var(--button-color) 30%, transparent);
  color: var(--button-contrast);
  text-decoration: none;
  transform: translate(1px, 1px);
}

.custom-button:hover::after {
  transform: translate(1px, -1px);
}

.custom-button:active {
  box-shadow: 0 0 0 transparent;
  transform: translate(2px, 2px);
}

.custom-button:focus-visible {
  outline: 2px dashed var(--button-color);
  outline-offset: 3px;
  text-decoration: none;
}

/* Keep the Markdown link styles from overriding the button treatment. */
.prose a.custom-button {
  color: var(--button-contrast);
  text-decoration: none;
}

.prose a.custom-button:hover {
  color: var(--button-contrast);
}

.button-xs {
  --button-padding: 0.25rem 0.6rem;
  --button-font-size: 0.75rem;
  --button-gap: 0.4rem;
  --button-shadow: 2px;
}

.button-sm {
  --button-padding: 0.4rem 0.75rem;
  --button-font-size: 0.8125rem;
  --button-gap: 0.5rem;
  --button-shadow: 2px;
}

.button-md {
  --button-padding: 0.55rem 0.95rem;
  --button-font-size: 0.875rem;
}

.button-lg {
  --button-padding: 0.7rem 1.1rem;
  --button-font-size: 1rem;
  --button-gap: 0.75rem;
}

.button-xl {
  --button-padding: 0.85rem 1.3rem;
  --button-font-size: 1.125rem;
  --button-gap: 0.85rem;
  --button-shadow: 4px;
}

.button-primary {
  --button-color: var(--accent);
  --button-contrast: var(--button-default-contrast);
}

.button-custom-color {
  --button-contrast: color-mix(
    in srgb,
    var(--button-color) 68%,
    var(--foreground)
  );
  --button-fill: color-mix(in srgb, var(--button-color) 17%, var(--background));
  --button-fill-hover: color-mix(
    in srgb,
    var(--button-color) 30%,
    var(--background)
  );
  --button-border: color-mix(in srgb, var(--button-color) 58%, var(--border));
}

.button-secondary {
  --button-color: var(--foreground);
  --button-contrast: var(--background);
}

.button-success {
  --button-color: #287a54;
  --button-contrast: #f7fffb;
}

.button-danger {
  --button-color: #b83b3b;
  --button-contrast: #fff8f8;
}

.button-warning {
  --button-color: #e7b73d;
  --button-contrast: #241b04;
}

.button-info {
  --button-color: #257c91;
  --button-contrast: #f4fdff;
}

.button-light {
  --button-color: #e8e8e8;
  --button-contrast: #282728;
}

.button-dark {
  --button-color: #282728;
  --button-contrast: #fdfdfd;
}

.button-pink {
  --button-color: #be185d;
  --button-contrast: #fff7fb;
}

.button-purple {
  --button-color: #6d28d9;
  --button-contrast: #fbf8ff;
}

.button-indigo {
  --button-color: #4338ca;
  --button-contrast: #f8f8ff;
}

.button-teal {
  --button-color: #0f766e;
  --button-contrast: #f3fffd;
}

.button-cyan {
  --button-color: #0e7490;
  --button-contrast: #f2fdff;
}

.button-orange {
  --button-color: #c2410c;
  --button-contrast: #fff8f4;
}

html[data-theme="dark"] .button-success {
  --button-color: #78d6a8;
  --button-contrast: #10231a;
}

html[data-theme="dark"] .button-danger {
  --button-color: #ff938b;
  --button-contrast: #2d1110;
}

html[data-theme="dark"] .button-warning {
  --button-color: #ffd166;
  --button-contrast: #2a2108;
}

html[data-theme="dark"] .button-info {
  --button-color: #69c7dc;
  --button-contrast: #0c252b;
}

html[data-theme="dark"] .button-light {
  --button-color: #e7e9ee;
  --button-contrast: #232839;
}

html[data-theme="dark"] .button-dark {
  --button-color: #0f1420;
  --button-contrast: #f4f6fb;
}

html[data-theme="dark"] .button-pink {
  --button-color: #f9a8d4;
  --button-contrast: #2b0917;
}

html[data-theme="dark"] .button-purple {
  --button-color: #c4b5fd;
  --button-contrast: #1f0f42;
}

html[data-theme="dark"] .button-indigo {
  --button-color: #a5b4fc;
  --button-contrast: #17173a;
}

html[data-theme="dark"] .button-teal {
  --button-color: #5eead4;
  --button-contrast: #0b2421;
}

html[data-theme="dark"] .button-cyan {
  --button-color: #67e8f9;
  --button-contrast: #0a272d;
}

html[data-theme="dark"] .button-orange {
  --button-color: #fdba74;
  --button-contrast: #2b1405;
}

.button-text-white {
  --button-contrast: #fff;
}

.button-text-black {
  --button-contrast: #000;
}

.button-text-gray {
  --button-contrast: #374151;
}

.button-text-light {
  --button-contrast: #f3f4f6;
}

.button-text-dark {
  --button-contrast: #111827;
}

@media (prefers-reduced-motion: reduce) {
  .custom-button,
  .custom-button::after {
    transition: none;
  }

  .custom-button:hover,
  .custom-button:active {
    transform: none;
  }
}

按钮样式使用原生 CSS 与 color-mix(),不依赖 Tailwind 工具类;只要项目定义了 --background、--foreground、--accent、--border 等主题变量即可复用。自定义颜色会被转换为低饱和的浅色填充,而不是直接铺满高饱和色块。

第四步:在 Markdown 中使用

提示框语法

支持五种类型:note、tip、info、warning、danger。提示框内的第一个段落会自动渲染为加粗标题。

:::note
这是一个普通的注意提示框。
:::

:::tip
这是一个友好的提示信息。
:::

:::info
这是一个信息提示框,用于提供额外信息。
:::

:::warning
这是一个警告提示框,用于提醒用户注意。
:::

:::danger
这是一个危险警告,用于提醒用户谨慎操作。
:::

按钮语法

按钮使用 :::button{属性...} 语法,支持以下属性:

属性说明预设值自定义示例
href按钮链接地址任意 URLhref="https://example.com"
size按钮尺寸xs, sm, md, lg, xlsize="1.5rem"
color主色/语义色调primary, secondary, success, danger, warning, info, light, dark, pink, purple, indigo, teal, cyan, orangecolor="#ff6b6b"
textColor文字颜色white, black, gray, light, darktextColor="#2d3436"
padding内边距任意 CSS 值padding="1rem 2rem"
borderRadius圆角任意 CSS 值borderRadius="50px"
target链接打开方式默认 _blanktarget="_self"

size、color、textColor 使用预设值时生成对应的 CSS 类名;使用非预设值时,插件会写入 --button-font-size、--button-color、--button-contrast 等 CSS 变量,再由统一样式决定最终外观。padding 和 borderRadius 也会分别映射到 --button-padding 与 --button-radius。

预设尺寸

:::button{href="https://example.com" size="xs"}
超小号按钮
:::

:::button{href="https://example.com" size="sm"}
小号按钮
:::

:::button{href="https://example.com" size="md"}
中号按钮
:::

:::button{href="https://example.com" size="lg"}
大号按钮
:::

:::button{href="https://example.com" size="xl"}
超大号按钮
:::

预设颜色

:::button{href="https://example.com" color="primary"}
主要按钮
:::

:::button{href="https://example.com" color="danger"}
危险按钮
:::

:::button{href="https://example.com" color="warning" textColor="black"}
警告按钮(深色文字)
:::

完全自定义

:::button{href="https://example.com" size="0.75rem"}
超小字体按钮
:::

:::button{href="https://example.com" color="#ff6b6b"}
自定义红色按钮
:::

:::button{href="https://example.com" color="#ffeaa7" textColor="#2d3436"}
自定义黄色按钮深色文字
:::

:::button{href="https://example.com" padding="1rem 2rem"}
自定义内边距按钮
:::

:::button{href="https://example.com" borderRadius="2rem"}
圆角按钮
:::

组合使用

:::button{href="https://example.com" size="lg" color="success"}
大号成功按钮
:::

:::button{href="https://example.com" size="sm" color="danger"}
小号危险按钮
:::

:::button{href="https://example.com" color="#fd79a8" padding="1.5rem 3rem" borderRadius="50px"}
完全自定义按钮
:::

更多注意事项

插件注册顺序

处理流程如下:

  1. remark-directive 将 :::name{...} 语法解析为 directive AST 节点
  2. remark-admonitions / remark-button 将匹配到的 directive 节点转换为 HTML

关于 TypeScript

如果你使用 astro check 做类型检查,可能需要为插件文件添加类型声明。推荐在 plugins/ 目录下创建对应的声明文件:

// plugins/remark-admonitions.d.ts
declare module "./plugins/remark-admonitions" {
  const value: () => (tree: any) => void;
  export default value;
}

// plugins/remark-button.d.ts
declare module "./plugins/remark-button" {
  const value: () => (tree: any) => void;
  export default value;
}

CSS 框架兼容性

已知限制

  1. 按钮默认在新标签页打开(target="_blank"),如需当前页跳转请指定 target="_self"
  2. 按钮的 rel 属性固定为 "noopener noreferrer nofollow",无法自定义
  3. 提示框的第一个段落始终被渲染为标题,无法禁用
  4. 提示框目前不支持自定义属性传入,仅支持五种预设类型

在以下平台分享此文章:

上一篇
尝试着接入了一个在线游戏平台
下一篇
挂机赚钱分享