快速上手指南

rehype-smart-links 是一个为 Markdown 链接添加智能功能的 rehype 插件。本指南将帮助你快速安装和配置插件。

安装

使用你偏好的包管理器安装插件:

BASH
# 使用 npm
npm install rehype-smart-links

# 使用 yarn
yarn add rehype-smart-links

# 使用 pnpm
pnpm add rehype-smart-links

基础配置

在 Astro 中使用

astro.config.mjs 文件中添加插件:

JS
import { defineConfig } from 'astro/config';
import rehypeSmartLinks from 'rehype-smart-links';

export default defineConfig({
  markdown: {
    rehypePlugins: [
      // 基本用法(默认设置)
      rehypeSmartLinks,
      
      // 或使用自定义选项
      [rehypeSmartLinks, {
        internalLinkClass: 'internal-link',
        brokenLinkClass: 'broken-link',
        externalLinkClass: 'external-link',
        routesFile: './.smart-links-routes.json', // 路由文件路径
        includeAllFiles: false,  // 是否包含所有文件类型
      }]
    ]
  }
});

在 Next.js 中使用

在 Next.js 项目中,你可以使用 MDX 和 rehype 插件:

JS
// next.config.js
const withMDX = require('@next/mdx')({
  options: {
    rehypePlugins: [
      require('rehype-smart-links')
    ]
  }
})

module.exports = withMDX({
  pageExtensions: ['js', 'jsx', 'md', 'mdx'],
})

在 Gatsby 中使用

在 Gatsby 项目中配置:

JS
// gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-mdx`,
      options: {
        rehypePlugins: [
          require('rehype-smart-links')
        ],
      },
    },
  ],
}

添加样式

插件会为不同类型的链接添加以下 CSS 类:

  • internal-link: 应用于内部链接(指向你网站内的页面)
  • broken-link: 应用于断开的内部链接(指向不存在的页面)
  • external-link: 应用于外部链接(指向其他网站)

你可以在全局 CSS 文件中添加样式:

CSS
/* 内部链接样式 */
.internal-link {
  color: #3b82f6;
  position: relative;
}

.internal-link::after {
  content: '';
  position: absolute;
  width: 100%;
  height: 1px;
  bottom: -2px;
  left: 0;
  background-color: currentColor;
  transform: scaleX(0);
  transform-origin: left;
  transition: transform 0.3s ease;
}

.internal-link:hover::after {
  transform: scaleX(1);
}

/* 断开链接样式 */
.broken-link {
  color: #ef4444;
  text-decoration: line-through;
  opacity: 0.8;
}

/* 外部链接样式 */
.external-link {
  color: #10b981;
  position: relative;
  padding-right: 1.2em;
}

.external-link::after {
  content: '↗';
  position: absolute;
  right: 0;
  font-size: 0.8em;
}

高级配置选项

rehype-smart-links 提供了多种配置选项:

选项类型默认值描述
internalLinkClassstring'internal-link'应用于内部链接的 CSS 类
brokenLinkClassstring'broken-link'应用于断开链接的 CSS 类
externalLinkClassstring'external-link'应用于外部链接的 CSS 类
contentobject{ type: 'text', value: '↗' }添加到外部链接的内容
contentClassstring'external-icon'应用于外部链接图标的 CSS 类
routesFilestring'./.smart-links-routes.json'路由映射文件的路径(应与CLI生成的位置匹配)
includeAllFilesbooleanfalse是否包含所有文件在路由检查中
targetstring'_blank'外部链接的 target 属性
relstring'noopener noreferrer'外部链接的 rel 属性
externalLinkAttributesobject{ target: '_blank', rel: 'noopener noreferrer' }应用于外部链接的 HTML 属性
wrapperTemplatefunction自定义链接包装模板函数

查看 高级演示 获取更多自定义选项的示例。

相关链接 Astro Tailwind CSS DaisyUI
资源 GitHub NPM