Search code examples
htmlmarkdowngatsbyconvertersnetlify-cms

How to transform markdown to html like the plugin gatsby-transformer-remark does (for NetlifyCMS)


I'd like to transform a markdown string to html the same way as the plugin gatsby-transformer-remark does.

So far I used showdown. This works ok, but it's missing features like transforming the image editor component.

I'd like to transform markdown with the same alghorithm as the plugin gatsby-transformer-remark.

Is there a ready made solution for this?


Solution

  • After reverse-engineering gatsby-transformer-remark, I found this solution:

    const remark = require(`remark`);
    const mdastToHast = require(`mdast-util-to-hast`);
    const hastToHtml = require(`hast-util-to-html`);
    
    const remarker = new remark();
    
    const markdownAst = remarker.parse(data.body);
    const htmlAst = mdastToHast(markdownAst, { allowDangorousHtml: true });
    const htmlRaw = hastToHtml(htmlAst, { allowDangorousHtml: true });
    
    const html = htmlRaw
      .split('<img src="uploads/')
      .join('<img src="/uploads/');