如何配置 remark.js 来解析 Markdown 中嵌入的 HTML?

Gre*_*son 6 javascript markdown remarkjs

我用来remark获取包含 HTML 标签的 Markdown 文档的 AST。当我运行这个时:

const remark = require('remark')
const result = remark.parse('<h1>First</h1>')
console.log(JSON.stringify(result, null, 2))
Run Code Online (Sandbox Code Playgroud)

我得到一个包含 1 级标题的 AST:

{
  "type": "root",
  "children": [
    {
      "type": "heading",
      "depth": 1,
      "children": [
        {
          "type": "text",
          "value": "Title",
          "position": {
            "start": {
              "line": 1,
              "column": 3,
              "offset": 2
            },
            "end": {
              "line": 1,
              "column": 8,
              "offset": 7
            }
          }
        }
      ],
      "position": {
        "start": {
          "line": 1,
          "column": 1,
          "offset": 0
        },
        "end": {
          "line": 1,
          "column": 8,
          "offset": 7
        }
      }
    },
    {
      "type": "paragraph",
      "children": [
        {
          "type": "text",
          "value": "body",
          "position": {
            "start": {
              "line": 2,
              "column": 1,
              "offset": 8
            },
            "end": {
              "line": 2,
              "column": 5,
              "offset": 12
            }
          }
        }
      ],
      "position": {
        "start": {
          "line": 2,
          "column": 1,
          "offset": 8
        },
        "end": {
          "line": 2,
          "column": 5,
          "offset": 12
        }
      }
    }
  ],
  "position": {
    "start": {
      "line": 1,
      "column": 1,
      "offset": 0
    },
    "end": {
      "line": 2,
      "column": 5,
      "offset": 12
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但如果我改用显式h1标签:

const remark = require('remark')
const result = remark.parse('<h1>Title</h1>\nbody') # <- note change
console.log(JSON.stringify(result, null, 2))
Run Code Online (Sandbox Code Playgroud)

html我得到一个包含标签文本及其内容的节点类型:

{
  "type": "root",
  "children": [
    {
      "type": "html",
      "value": "<h1>Title</h1>\nbody",
      "position": {
        "start": {
          "line": 1,
          "column": 1,
          "offset": 0
        },
        "end": {
          "line": 2,
          "column": 5,
          "offset": 19
        }
      }
    }
  ],
  "position": {
    "start": {
      "line": 1,
      "column": 1,
      "offset": 0
    },
    "end": {
      "line": 2,
      "column": 5,
      "offset": 19
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我想在第二种情况下获得与第一种情况相同的 AST,即我想remark解析 HTML。我希望它默认这样做,因为 Markdown 允许包含 HTML;如果这是由解析器配置选项启用的,我还没有找到它。非常欢迎指点。

小智 6

也许您想要使用的是rehype-raw插件。它允许您解析 markdown 中嵌入的 HTML。请在此处查看相关讨论。