Markdown - BunDocumentation Index Search...⌘KInstall Bun Search...Navigation Utilities MarkdownRuntimePackage ManagerBundlerTest RunnerGuidesReferenceBlogFeedback:first-child]:!hidden peer-[.is-custom]:[&>:first-child]:sm:!hidden peer-[.is-custom]:[&>:first-child]:md:!hidden peer-[.is-custom]:[&>:first-child]:lg:!hidden peer-[.is-custom]:[&>:first-child]:xl:!hidden">Get StartedWelcome to BunInstallationQuickstartTypeScriptTypeScript 6 and 7bun initbun createCore RuntimeBun RuntimeWatch ModeDebuggingREPLbunfig.tomlFile & Module SystemFile TypesModule ResolutionJSXAuto-installPluginsFile System RouterHTTP serverServerRoutingCookiesTLSError HandlingMetricsNetworkingFetchWebSocketsTCPUDPDNSData & StorageCookiesFile I/OStreamsBinary DataArchiveSQLSQLiteS3RedisConcurrencyWorkersProcess & SystemEnvironment VariablesShellSpawnWebViewCronInterop & ToolingNode-APIFFIC CompilerTranspilerUtilitiesCSRF ProtectionSecretsConsoleTOMLYAMLMarkdownJSON5JSONLHTMLRewriterImageHashingGlobSemverColorUtilsStandards & CompatibilityGlobalsBun APIsWeb APIsNode.js CompatibilityContributingRoadmapBenchmarkingContributingBuilding WindowsBindgenLicense On this pageBun.markdown.html()OptionsAutolinksHeading IDsBun.markdown.render()Callback signatureBlock callbacksList item metaInline callbacksExamplesCustom HTML with classesStripping all formattingOmitting elementsANSI terminal outputNested list numberingCode block syntax highlightingParser optionsBun.markdown.react()Server-side renderingComponent overridesAvailable overridesReact 18 and olderParser optionsUtilitiesMarkdown Copy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_n4ctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed"> *]:[overflow-wrap:anywhere]"> Copy pagespan]:line-clamp-1 overflow-hidden group flex items-center py-0.5 gap-1 text-sm text-gray-950/50 dark:text-white/50 group-hover:text-gray-950/70 dark:group-hover:text-white/70 rounded-none rounded-r-xl border px-3 border-gray-200 aspect-square dark:border-white/[0.07] bg-background-light dark:bg-background-dark hover:bg-gray-600/5 dark:hover:bg-gray-200/5" aria-label="More actions" type="button" id="radix-_R_1cctdbsnlht5lebsnpfdb_" aria-haspopup="menu" aria-expanded="false" data-state="closed"> Unstable API — This API is under active development and may change in future versions of Bun.
Bun includes a fast, built-in Markdown parser written in Zig. It supports GitHub Flavored Markdown (GFM) extensions and provides three APIs:
Bun.markdown.html() — render Markdown to an HTML string
Bun.markdown.render() — render Markdown with custom callbacks for each element
Bun.markdown.react() — render Markdown to React JSX elements
Bun.markdown.html()
Convert a Markdown string to HTML.
Yes NoSuggest editsRaise issueYAMLPreviousJSON5Next⌘I xgithubdiscordyoutubePowered byThis documentation is built and hosted on Mintlify, a developer documentation platform
Fetch the complete documentation index at: /docs/llms.txt
Use this file to discover all available pages before exploring further.
Skip to main contentBun home pageParse and render Markdown with Bun’s built-in Markdown API, supporting GFM extensions and custom rendering callbacks
const html = Bun.markdown.html("# Hello **world**");
// "Hello world\n"
GFM extensions like tables, strikethrough, and task lists are enabled by default:
const html = Bun.markdown.html(` | Feature | Status | |-------------|--------| | Tables | ~~done~~ | | Strikethrough| ~~done~~ | | Task lists | done | `);Options Pass an options object as the second argument to configure the parser:
const html = Bun.markdown.html("some markdown", {
tables: true, // GFM tables (default: true)
strikethrough: true, // GFM strikethrough (default: true)
tasklists: true, // GFM task lists (default: true)
tagFilter: true, // GFM tag filter for disallowed HTML tags
autolinks: true, // Autolink URLs, emails, and www. links
});
All available options:
OptionDefaultDescriptiontablesfalseGFM tablesstrikethroughfalseGFM strikethrough (~~text~~)tasklistsfalseGFM task lists (- [x] item)autolinksfalseEnable autolinks — see AutolinksheadingsfalseHeading IDs and autolinks — see Heading IDshardSoftBreaksfalseTreat soft line breaks as hard breakswikiLinksfalseEnable [[wiki links]]underlinefalse__text__ renders as instead of latexMathfalseEnable $inline$ and $$display$$ mathcollapseWhitespacefalseCollapse whitespace in textpermissiveAtxHeadersfalseATX headers without space after #noIndentedCodeBlocksfalseDisable indented code blocksnoHtmlBlocksfalseDisable HTML blocksnoHtmlSpansfalseDisable inline HTMLtagFilterfalseGFM tag filter for disallowed HTML tags
Autolinks
Pass true to enable all autolink types, or an object for granular control:
// Enable all autolinks (URL, WWW, email)
Bun.markdown.html("Visit www.example.com", { autolinks: true });
// Enable only specific types
Bun.markdown.html("Visit www.example.com", {
autolinks: { url: true, www: true },
});
Heading IDs
Pass true to enable both heading IDs and autolink headings, or an object for granular control:
// Enable heading IDs and autolink headings
Bun.markdown.html("## Hello World", { headings: true });
// 'Hello World\n'
// Enable only heading IDs (no autolink)
Bun.markdown.html("## Hello World", { headings: { ids: true } });
// 'Hello World\n'
Bun.markdown.render()
Parse Markdown and render it using custom JavaScript callbacks. This gives you full control over the output format — you can generate HTML with custom classes, React elements, ANSI terminal output, or any other string format.
const result = Bun.markdown.render("# Hello **world**", {
heading: (children, { level }) => `${level} class="title">${children}${level}>`,
strong: children => `${children}`,
paragraph: children => `${children}
`,
});
// 'Hello world'
Callback signature
Each callback receives:
children — the accumulated content of the element as a string
meta (optional) — an object with element-specific metadata
Return a string to replace the element’s rendering. Return null or undefined to omit the element from the output entirely. If no callback is registered for an element, its children pass through unchanged.
Block callbacks
CallbackMetaDescriptionheading{ level, id? }Heading level 1–6. id is set when headings: { ids: true } is enabledparagraph—Paragraph blockblockquote—Blockquote blockcode{ language? }Fenced or indented code block. language is the info-string when specified on the fencelist{ ordered, start?, depth }depth is nesting level (0 = top-level). start is set for ordered listslistItem{ index, depth, ordered, start?, checked? }See List item meta belowhr—Horizontal ruletable—Table blockthead—Table headtbody—Table bodytr—Table rowth{ align? }Table header cell. align is "left", "center", "right", or absenttd{ align? }Table data cellhtml—Raw HTML content
List item meta
The listItem callback receives everything needed to render markers directly:
index — 0-based position within the parent list
depth — the parent list’s nesting level (0 = top-level)
ordered — whether the parent list is ordered
start — the parent list’s start number (only when ordered is true)
checked — task list state (only for - [x] / - [ ] items)
Inline callbacks
CallbackMetaDescriptionstrong—Strong emphasis (**text**)emphasis—Emphasis (*text*)link{ href: string, title?: string }Linkimage{ src: string, title?: string }Imagecodespan—Inline code (`code`)strikethrough—Strikethrough (~~text~~)text—Plain text content
Examples
Custom HTML with classes
const html = Bun.markdown.render("# Title\n\nHello **world**", {
heading: (children, { level }) => `${level} class="heading heading-${level}">${children}${level}>`,
paragraph: children => `${children}
`,
strong: children => `${children}`,
});
Stripping all formatting
const plaintext = Bun.markdown.render("# Hello **world**", {
heading: children => children,
paragraph: children => children,
strong: children => children,
emphasis: children => children,
link: children => children,
image: () => "",
code: children => children,
codespan: children => children,
});
// "Hello world"
Omitting elements
Return null or undefined to remove an element from the output:
const result = Bun.markdown.render("# Title\n\n\n\nHello", {
image: () => null, // Remove all images
heading: children => children,
paragraph: children => children + "\n",
});
// "Title\nHello\n"
ANSI terminal output
const ansi = Bun.markdown.render("# Hello\n\nThis is **bold** and *italic*", {
heading: (children, { level }) => `\x1b[1;4m${children}\x1b[0m\n`,
paragraph: children => children + "\n",
strong: children => `\x1b[1m${children}\x1b[22m`,
emphasis: children => `\x1b[3m${children}\x1b[23m`,
});
Nested list numbering
The listItem callback receives everything needed to render markers directly — no post-processing:
const result = Bun.markdown.render("1. first\n 1. sub-a\n 2. sub-b\n2. second", {
listItem: (children, { index, depth, ordered, start }) => {
const n = (start ?? 1) + index;
// 1. 2. 3. at depth 0, a. b. c. at depth 1, i. ii. iii. at depth 2
const marker = !ordered
? "-"
: depth === 0
? `${n}.`
: depth === 1
? `${String.fromCharCode(96 + n)}.`
: `${toRoman(n)}.`;
return " ".repeat(depth) + marker + " " + children.trimEnd() + "\n";
},
// Prepend a newline so nested lists are separated from their parent item's text
list: children => "\n" + children,
});
// 1. first
// a. sub-a
// b. sub-b
// 2. second
Code block syntax highlighting
const result = Bun.markdown.render("```js\nconsole.log('hi')\n```", {
code: (children, meta) => {
const lang = meta?.language ?? "";
return `${lang}">${children}`;
},
});
Parser options
Parser options are passed as a separate third argument:
const result = Bun.markdown.render(
"Visit www.example.com",
{
link: (children, { href }) => `[${children}](${href})`,
paragraph: children => children,
},
{ autolinks: true },
);
Bun.markdown.react()
Render Markdown directly to React elements. Returns a that you can use as a component return value.
function Markdown({ text }: { text: string }) {
return Bun.markdown.react(text);
}
Server-side rendering
Works with renderToString() and React Server Components:
import { renderToString } from "react-dom/server";
const html = renderToString(Bun.markdown.react("# Hello **world**"));
// "Hello world"
Component overrides
Replace any HTML element with a custom React component by passing it in the second argument, keyed by tag name:
function Code({ language, children }) {
return (
pre data-language={language}>
code>{children}code>
pre>
);
}
function Link({ href, title, children }) {
return (
a href={href} title={title} target="_blank" rel="noopener noreferrer">
{children}
a>
);
}
function Heading({ id, children }) {
return (
h2 id={id}>
a href={`#${id}`}>{children}a>
h2>
);
}
const el = Bun.markdown.react(
content,
{
pre: Code,
a: Link,
h2: Heading,
},
{ headings: { ids: true } },
);
Available overrides
Every HTML tag produced by the parser can be overridden:
OptionPropsDescriptionh1–h6{ id?, children }Headings. id is set when headings: { ids: true } is enabledp{ children }Paragraphblockquote{ children }Blockquotepre{ language?, children }Code block. language is the info string (e.g. "js")hr{}Horizontal rule (no children)ul{ children }Unordered listol{ start, children }Ordered list. start is the first item numberli{ checked?, children }List item. checked is set for task list itemstable{ children }Tablethead{ children }Table headtbody{ children }Table bodytr{ children }Table rowth{ align?, children }Table header celltd{ align?, children }Table data cellem{ children }Emphasis (*text*)strong{ children }Strong (**text**)a{ href, title?, children }Linkimg{ src, alt?, title? }Image (no children)code{ children }Inline codedel{ children }Strikethrough (~~text~~)br{}Hard line break (no children)
React 18 and older
By default, elements use Symbol.for('react.transitional.element') as the $$typeof symbol. For React 18 and older, pass reactVersion: 18 in the options (third argument):
function Markdown({ text }: { text: string }) {
return Bun.markdown.react(text, undefined, { reactVersion: 18 });
}
Parser options
All parser options are passed as the third argument:
const el = Bun.markdown.react("## Hello World", undefined, {
headings: { ids: true },
autolinks: true,
});
Was this page helpful?
Markdown - Bun,AI智能索引,全网链接索引,智能导航,网页索引
- Parse and render Markdown with Bun