compile()

Fungsi kompilasi utama. Mentransformasi Markdown atau MDX menjadi HTML atau format output lainnya menggunakan compiler Rust native.

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

Signature

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

Parameter

input

PropertiTipeDefaultDeskripsi
inputstringString sumber Markdown atau MDX

options?

PropertiTipeDefaultDeskripsi
options?CompileOptionsKonfigurasi kompilasi termasuk plugin

Return

PropertiTipeDeskripsi
outputstring | objectOutput kompilasi. String HTML secara default; string JSON untuk HAST/MDAST.
frontmatterRecord<string, unknown>Metadata frontmatter yang sudah di-parse ({} kosong jika tidak ada)
diagnosticsDiagnostic[]Array dari { level, message, start?, end? }
stats{ parseMs, transformMs, emitMs }Rincian timing (ms)
tocTocEntry[]Daftar isi yang diekstrak ([] kosong jika TOC dinonaktifkan)

Penggunaan

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 }

Contoh

Markdown dasar ke HTML

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

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

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

Input 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" });

Output 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", ... }] }

Output 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, ... }] }

Output MDX JS

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

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

console.log(result.output);
// JavaScript module string with MDX compiled to JSX