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

问题描述

我正在使用remark获取包含HTML标签的Markdown文档的AST。当我运行此命令时:

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

我得到了一个包含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,"offset": 7
        }
      }
    },{
      "type": "paragraph","value": "body","position": {
            "start": {
              "line": 2,"offset": 8
            },"end": {
              "line": 2,"column": 5,"offset": 12
            }
          }
        }
      ],"position": {
        "start": {
          "line": 2,"offset": 8
        },"end": {
          "line": 2,"offset": 12
        }
      }
    }
  ],"position": {
    "start": {
      "line": 1,"offset": 0
    },"end": {
      "line": 2,"offset": 12
    }
  }
}

但是,如果我改用显式的h1标签

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

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

{
  "type": "root","children": [
    {
      "type": "html","value": "<h1>Title</h1>\nbody","offset": 19
        }
      }
    }
  ],"offset": 19
    }
  }
}

我希望在第二种情况下获得与在第一种情况下相同的AST,即,我希望remark来解析HTML。我希望它认情况下会执行此操作,因为Markdown允许包含HTML。如果通过解析器配置选项启用了此功能,则无法找到它。指针将非常受欢迎。

解决方法

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