compile()

Основная функция компиляции. Преобразует Markdown или MDX в HTML и другие форматы с помощью нативного компилятора на Rust.

import { compile } from "@unifast/node";

Сигнатура

function compile(input: string, options?: CompileOptions): CompileResult

Параметры

input

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

options?

СвойствоТипПо умолчаниюОписание
options?CompileOptionsКонфигурация компиляции, включая плагины

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

СвойствоТипОписание
outputstring | objectСкомпилированный вывод. По умолчанию — строка HTML; JSON-строка для HAST/MDAST.
frontmatterRecord<string, unknown>Распарсенные метаданные frontmatter (пустой {}, если отсутствуют)
diagnosticsDiagnostic[]Массив { level, message, start?, end? }
stats{ parseMs, transformMs, emitMs }Разбивка времени (мс)
tocTocEntry[]Извлечённое оглавление (пустой [], если TOC отключён)

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

import { compile, gfm, frontmatter, toc, sanitize } from "@unifast/node";

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

# Hello, **world**!

| Column A | Column B |
|----------|----------|
| Cell 1   | Cell 2   |
`;

const result = compile(md, {
  inputKind: "md",       // "md" | "mdx"
  outputKind: "html",    // "html" | "hast" | "mdast" | "mdxJs"
  plugins: [gfm(), frontmatter(), toc({ maxDepth: 3 }), sanitize()],
});

console.log(result.output);
// <h1 id="hello-world">Hello, <strong>world</strong>!</h1>
// <table>...</table>

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

console.log(result.toc);
// [{ depth: 1, text: "Hello, world!", slug: "hello-world" }]

console.log(result.stats);
// { parseMs: 0.12, transformMs: 0.08, emitMs: 0.05 }

Примеры

Базовое преобразование Markdown в HTML

import { compile } from "@unifast/node";

const result = compile("# Hello, **world**!");

console.log(result.output);
// <h1 id="hello-world">Hello, <strong>world</strong>!</h1>

Вход MDX

import { compile } from "@unifast/node";

const mdx = `
import { Alert } from "./components";

# Hello

<Alert type="info">This is MDX!</Alert>
`;

const result = compile(mdx, { inputKind: "mdx" });

Вывод HAST

import { compile } from "@unifast/node";

const result = compile("# Hello", { outputKind: "hast" });
const hast = JSON.parse(result.output as string);

console.log(hast);
// { type: "root", children: [{ type: "element", tagName: "h1", ... }] }

Вывод MDAST

import { compile } from "@unifast/node";

const result = compile("# Hello", { outputKind: "mdast" });
const mdast = JSON.parse(result.output as string);

console.log(mdast);
// { type: "root", children: [{ type: "heading", depth: 1, ... }] }

Вывод MDX JS

import { compile } from "@unifast/node";

const result = compile(mdxSource, {
  inputKind: "mdx",
  outputKind: "mdxJs",
});

console.log(result.output);
// Строка JavaScript-модуля с MDX, скомпилированным в JSX