【发布时间】:2021-02-10 19:55:27
【问题描述】:
我正在使用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,
"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
}
}
}
但如果我使用显式的h1 标签:
const remark = require('remark')
const result = remark.parse('<h1>Title</h1>\nbody') # <- note change
console.log(JSON.stringify(result, null, 2))
我得到一个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
}
}
}
我希望在第二种情况下获得与第一种情况相同的 AST,即我希望 remark 解析 HTML。我希望它默认这样做,因为 Markdown 允许包含 HTML;如果这是由解析器配置选项启用的,我找不到它。非常欢迎指点。
【问题讨论】:
-
如果你用空行将标题与正文分开,它是如何工作的(
<h1>Title</h1>\n\nbody
标签: javascript markdown remarkjs