How to parse markdown to json using remark
Asked Answered
W

1

4

The remark site has a link to an AST explorer for the output of remark - https://astexplorer.net/#/gist/0a92bbf654aca4fdfb3f139254cf0bad/ffe102014c188434c027e43661dbe6ec30042ee2

What I cannot find is how to do the parsing to AST - all the examples convert to HTML.

I have this code


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))
    })

But I am getting a couple of errors here that I do not know how to get around

[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`
Weekday answered 4/8, 2021 at 8:26 Comment(0)
C
6

You almost have it. Below I've simplified your code, removing unused and unnecessary parts.

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, "   "));

According to ChristianMurphy's GitHub Q/A:

unified.process() will try to take text, turn it into an AST, and back into text.

For your stated purpose, "...parsing to AST [JSON]", you don't need or want the "full-cycle process" that unified.process() is failing to complete, TypeError: Cannot 'process' without 'Compiler'. You merely want to parse the input and emit the syntax tree (AST) as JSON. The error here is because process(), after parsing your input (markdown string) and turning it into a syntax tree (AST), is then trying to "compile" it to some output format. However, you haven't supplied a compiler. But, as I understand your post, you don't need or want to compile the syntax tree into another output (language). So, change from process() to parse() and emit the resulting syntax tree as JSON.

Creight answered 23/12, 2021 at 18:33 Comment(1)
I should also note that I removed remark-gfm so I don't experience [remark-gfm] Warning: please upgrade to remark 13 to use this plugin . remark-gfm isn't necessary to accomplish the goal - as I understood it.Creight

© 2022 - 2024 — McMap. All rights reserved.