Back to all posts
Engineering

La magia de Markdown y unified.js

Markdown es el formato estándar para escribir documentación técnica y blogs. ¿Pero cómo lo conviertes a HTML?

El enfoque moderno es utilizar el ecosistema unified, el cual procesa el contenido a través de Árboles de Sintaxis Abstracta (AST, por sus siglas en inglés).

El Pipeline de Unified

Un pipeline típico se ve así:

  1. Analizar (Parse): Convierte una cadena a AST (usando remark-parse).
  2. Transformar (Transform): Modifica el AST (p. ej., añadiendo resaltado de sintaxis con remark-rehype y rehype-highlight).
  3. Cadenificar (Stringify): Convierte el AST de vuelta a una cadena HTML (usando 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());

¡Este enfoque te brinda la máxima flexibilidad y seguridad al manejar contenido generado por usuarios o al escribir tu propio generador de sitios estáticos!