compileToReact()

Компилирует входные данные Markdown или MDX и возвращает React-элементы напрямую вместе с frontmatter, диагностикой, статистикой и TOC.

import { compileToReact } from "@unifast/react";

Сигнатура

function compileToReact(
  input: string,
  options: CompileToReactOptions,
): CompileToReactResult

Параметры

input

СвойствоТипПо умолчаниюОписание
inputstringИсходный Markdown или MDX

options

Параметры компиляции плюс специфичная для React конфигурация

СвойствоТипПо умолчаниюОписание
createElementCreateElementФункция React createElement
FragmentunknownКомпонент React Fragment
components?ComponentMapОтображение имён HTML-тегов в React-компоненты

Расширяет CompileOptions — принимаются все остальные параметры компиляции.

Возвращаемое значение

СвойствоТипОписание
elementunknownКорневой React-элемент
frontmatterRecord<string, unknown>Распарсенные метаданные frontmatter
diagnosticsDiagnostic[]Предупреждения и ошибки
stats{ parseMs, transformMs, emitMs }Разбивка времени (мс)
tocTocEntry[]Извлечённое оглавление

Использование

import { createElement, Fragment } from "react";
import { compileToReact } from "@unifast/react";
import { gfm, frontmatter, toc } from "@unifast/node";

const { element, frontmatter: fm, toc: tocEntries, diagnostics, stats } = compileToReact(
  md,
  {
    createElement,
    Fragment,
    components: {
      h1: ({ children, ...props }) => <h1 className="title" {...props}>{children}</h1>,
      a: ({ children, ...props }) => <a target="_blank" {...props}>{children}</a>,
    },
    plugins: [gfm(), frontmatter(), toc()],
  },
);

Примеры

Базовое использование

import { createElement, Fragment } from "react";
import { compileToReact } from "@unifast/react";

const { element } = compileToReact(
  "# Hello, **world**!",
  { createElement, Fragment },
);

function Page() {
  return <div>{element}</div>;
}

С пользовательскими компонентами

import { createElement, Fragment } from "react";
import { compileToReact } from "@unifast/react";

const { element } = compileToReact(md, {
  createElement,
  Fragment,
  components: {
    h1: ({ children, ...props }) => (
      <h1 className="text-4xl font-bold" {...props}>{children}</h1>
    ),
    a: ({ children, ...props }) => (
      <a className="text-blue-500 underline" target="_blank" {...props}>{children}</a>
    ),
    code: ({ children, ...props }) => (
      <code className="bg-gray-100 rounded px-1" {...props}>{children}</code>
    ),
  },
});

Серверный рендеринг

import { createElement, Fragment } from "react";
import { renderToString } from "react-dom/server";
import { compileToReact } from "@unifast/react";

const { element } = compileToReact(md, { createElement, Fragment });
const html = renderToString(element);

console.log(html);
// Отрендеренная HTML-строка для SSR

Использование frontmatter и TOC

import { createElement, Fragment } from "react";
import { compileToReact } from "@unifast/react";
import { frontmatter, toc } from "@unifast/node";

const md = `---
title: My Page
---

# Introduction

## Setup

## Usage
`;

const result = compileToReact(md, {
  createElement,
  Fragment,
  plugins: [frontmatter(), toc()],
});

console.log(result.frontmatter);
// { title: "My Page" }

console.log(result.toc);
// [
//   { depth: 1, text: "Introduction", slug: "introduction" },
//   { depth: 2, text: "Setup", slug: "setup" },
//   { depth: 2, text: "Usage", slug: "usage" },
// ]