Back to all posts

The Magic of Markdown and unified.js

Markdown is the standard format for writing technical documentation and blogs. But how do you convert it into HTML?

The modern approach is to use the unified ecosystem, which processes content through Abstract Syntax Trees (ASTs).

The Unified Pipeline

A typical pipeline looks like this:

  1. Parse: Convert string to AST (using remark-parse).
  2. Transform: Modify the AST (e.g., adding syntax highlighting with remark-rehype and rehype-highlight).
  3. Stringify: Convert the AST back to HTML string (using rehype-stringify).
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkRehype from 'remark-rehype';
import rehypeHighlight from 'rehype-highlight';
import rehypeStringify from 'rehype-stringify';

const processor = unified()
  .use(remarkParse)
  .use(remarkRehype)
  .use(rehypeHighlight)
  .use(rehypeStringify);

const html = await processor.process('# Hello World');
console.log(html.toString());

This approach gives you maximum flexibility and security when handling user-generated content or writing your own static site generator!

Thanks for reading! Did you find this helpful?

Get in touch