Back to all posts
Engineering

Markdown 和 unified.js 的魔力

Markdown 是编写技术文档和博客的标准格式。但是您如何将它转换为 HTML?

现代方法是使用 unified 生态系统,它通过抽象语法树(AST)处理内容。

Unified 管道

一个典型的管道如下所示:

  1. 解析 (Parse):将字符串转换为 AST(使用 remark-parse)。
  2. 转换 (Transform):修改 AST(例如,使用 remark-rehype 和 rehype-highlight 添加语法高亮)。
  3. 字符串化 (Stringify):将 AST 转换回 HTML 字符串(使用 rehype-stringify)。
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import rehypeHighlight from 'rehype-highlight';
import rehypeStringify from 'rehype-stringify';

const processor = unified()
  .use(remarkParse)
  .use(remarkRehype)
  .use(rehypeHighlight)
  .use(rehypeStringify);

const html = await processor.process('# Hello World');
console.log(html.toString());

这种方法在处理用户生成的内容或编写自己的静态站点生成器时,为您提供了最大的灵活性和安全性!