【问题标题】:How to parse markdown to json using remark如何使用备注将markdown解析为json
【发布时间】:2023-03-03 19:05:01
【问题描述】:

remark site 有一个指向 AST explorer 的链接,用于输出 remark - https://astexplorer.net/#/gist/0a92bbf654aca4fdfb3f139254cf0bad/ffe102014c188434c027e43661dbe6ec30042ee2

我找不到的是如何对 AST 进行解析 - 所有示例都转换为 html。

我有这个代码


import {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkGfm from 'remark-gfm' // git flavoured markdown

const content = `
# My header

This is my content

 - abc
 - def
 
`;

unified()
    .use(remarkParse)
    .use(remarkGfm)
    .process('# Hi\n\n*Hello*, world!')
    .then((file) => {
        console.log(String(file))
    })

但是这里出现了一些我不知道如何解决的错误

[remark-gfm] Warning: please upgrade to remark 13 to use this plugin
file:///markdown/node_modules/unified/lib/index.js:520
    throw new TypeError('Cannot `' + name + '` without `Compiler`')
          ^

TypeError: Cannot `process` without `Compiler`

【问题讨论】:

    标签: node.js remarkjs


    【解决方案1】:

    你几乎拥有它。下面我简化了您的代码,删除了未使用和不必要的部分。

    import {unified} from 'unified'
    import remarkParse from 'remark-parse'
    
    let myResult = unified()
        .use(remarkParse)
        .parse('# Hi\n\n*Hello*, world!');
    
    console.log(JSON.stringify(myResult, null, "   "));
    

    根据ChristianMurphy's GitHub Q/A

    unified.process() 将尝试获取文本,将其转换为 AST,然后再转换为文本。

    出于您声明的目的,“...解析为 AST [JSON]”,您不需要或不希望 @ 987654323@ 未能完成,TypeError: Cannot 'process' without 'Compiler'。您只想解析输入并将语法树 (AST) 作为 JSON 发出。这里的错误是因为process() 在解析您的输入(降价字符串)并将其转换为语法树 (AST) 之后,然后尝试将其“编译”为某种输出格式。但是,您还没有提供编译器。但是,据我了解您的帖子,您不需要或不想将语法树编译成另一种输出(语言)。因此,将 process() 更改为 parse() 并将生成的语法树作为 JSON 发出。

    【讨论】:

    • 我还应该注意我删除了 remark-gfm 所以我没有体验到 [remark-gfm] Warning: please upgrade to remark 13 to use this pluginremark-gfm 不是实现目标所必需的——据我所知。
    猜你喜欢
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    相关资源
    最近更新 更多