Converts from Markdown to HTML fully client-side

Last modified by Manuel Leduc on 2026/02/05 17:22

Content

Steps

The snippet below presents how to parse Markdown content and convert it to HTML.
You can follow the steps mentionned in the snippet's comments.

import { Container } from "inversify";
import type { UniAstToHTMLConverter } from "@xwiki/cristal-uniast-html";
import type { MarkdownToUniAstConverter } from "@xwiki/rendering-uniast-markdown";

async function markdownToHTML(
  source: string,
  container: Container,
): Promise<string> {
  // Mardown to uniast to html
  // Step 1: resolve the markdown parser
  const md = container.get<MarkdownToUniAstConverter>(
    "MarkdownToUniAstConverter",
  );

  // Step 2: parse the markdown to get a uniast object
  const uniAst = await md.parseMarkdown(source);

  if (uniAst instanceof Error) {
    throw uniAst;
  }

  // Step 3: resolve the html serializer
  const html = container.get<UniAstToHTMLConverter>("UniAstToHTMLConverter");
  // Step 4: serialize the uniast object to HTML
  const toHtml = html.toHtml(uniAst);
  if (toHtml instanceof Error) {
    throw toHtml;
  }
  return toHtml;
}

Get Connected