SuperAPI AI 工具集

tanstack-markdown-render-markdown

写作与研究

查看项目

更新于 10-16 09:23

技能介绍

用途

TanStack Markdown 用于将受控的博客和文档内容解析为可序列化的 AST,并渲染为 HTML。它面向框架中立的使用场景,提供独立的解析与渲染入口,便于在服务端或构建阶段预解析、缓存并重复渲染。

主要能力

  • 解析:parseMarkdown 处理完整文档,parseInline 仅处理行内语法。
  • 渲染:renderHtml、renderDocument、renderBlock、renderInline 将源字符串或已有 MarkdownDocument 渲染为 HTML。
  • 配置:解析时可启用 frontmatter、自定义 headingIds;渲染时可添加 headingAnchors、highlighter、codeLineNumbers 等仅渲染选项。
  • 行为契约:解析同步、确定、规范化行尾;原始 HTML 仅在 allowHtml: true 时识别;链接和图片会移除不安全可执行协议;引用定义在块解析前按大小写不敏感解析;脚注按首次引用顺序渲染,ID 防冲突并支持重复引用回链;代码围栏元数据记录在 AST 中,高亮由外部处理。

使用方式

安装框架中立包:

pnpm add @tanstack/markdown

基础渲染:

import { renderHtml } from '@tanstack/markdown/html'

const source = `# Release notes

Small browser bundle

Serializable AST

Safe HTML defaults`

const html = renderHtml(source)
console.log(html)

解析一次并渲染可复用文档:

import { renderHtml } from '@tanstack/markdown/html'
import { parseMarkdown } from '@tanstack/markdown/parser'
import type { MarkdownDocument } from '@tanstack/markdown'

const source = `# Guide

Read the [installation notes](/installation).`

const document = parseMarkdown(source)
const serialized = JSON.stringify(document)
const restored = JSON.parse(serialized) as MarkdownDocument
const html = renderHtml(restored)
console.log(html)

解析时配置 frontmatter 和标题 ID:

import { renderHtml } from '@tanstack/markdown/html'
import { parseMarkdown } from '@tanstack/markdown/parser'

const source = `---
title: Installation
published: true
---

# Install

## Install`

const document = parseMarkdown(source, {
  frontmatter: true,
  headingIds(text, lineIndex) {
    const slug = text.toLowerCase().replaceAll(' ', '-')
    return `docs-${lineIndex}-${slug}`
  },
})

console.log(document.frontmatter)
console.log(renderHtml(document))

渲染时添加可见标题锚点:

import { renderHtml } from '@tanstack/markdown/html'
import { parseMarkdown } from '@tanstack/markdown/parser'

const document = parseMarkdown('# API')

const html = renderHtml(document, {
  headingAnchors: {
    content: '#',
    className: 'heading-anchor',
    ariaHidden: true,
    tabIndex: -1,
  },
})
console.log(html)

仅解析行内内容:

import { parseInline, renderInline } from '@tanstack/markdown'

const nodes = parseInline('Use **stable** APIs and `parseMarkdown`.')
const html = nodes.map(node => renderInline(node)).join('')
console.log(html)

适用场景

适用于受控的博客和文档内容渲染,例如在构建阶段预解析 Markdown 并缓存 AST,在运行时重复渲染为 HTML,或与 React、Octane 等渲染技能配合使用。

限制

  • 不追求完整 CommonMark、GFM、MDX 或任意 HTML 解析;Setext 标题和自动 URL 链接不在支持范围内。
  • 原始 HTML 仅在 allowHtml: true 时识别。
  • 解析选项(frontmatter、headingIds、allowHtml、解析器状态、解析器/转换扩展)必须在缓存 AST 前应用;仅渲染选项(headingAnchors、highlighter、codeLineNumbers)可在渲染已有文档时应用。
  • AST 为公开但 pre-1.0,升级若改变节点契约需重新生成持久化文档。
  • 代码高亮由外部处理,本包仅记录代码围栏元数据。
  • 完整文档渲染器对字符串输入每次调用都会解析,传入 MarkdownDocument 可跳过重复解析。
  • parseInline 不提取文档级引用或脚注定义,除非显式提供内部解析器状态。