Advanced Markdown processing capabilities including front matter parsing, content extraction, heading management, and link resolution. These utilities provide comprehensive tools for processing Markdown files in static site generators.
/**
* Options for writing heading IDs with optional overwrite flag
*/
type WriteHeadingIDOptions = SluggerOptions & {
overwrite?: boolean;
};
type SluggerOptions = {
maintainCase?: boolean;
};
/**
* Content paths for base and localized directories
*/
type ContentPaths = {
contentPath: string;
contentPathLocalized: string;
};
/**
* Maps aliased source paths to permalinks
*/
type SourceToPermalink = Map<string, string>;/**
* Default front matter parser using gray-matter
*/
const DEFAULT_PARSE_FRONT_MATTER: DefaultParseFrontMatter;parseMarkdownFileComplete markdown file parsing with front matter, title, and excerpt extraction.
/**
* Complete markdown file parsing with front matter, title, and excerpt extraction
* @param params - Parsing parameters
* @param params.filePath - Path to the markdown file
* @param params.fileContent - Raw markdown content
* @param params.parseFrontMatter - Front matter parser (optional)
* @param params.removeContentTitle - Whether to remove title from content (optional)
* @returns Promise resolving to parsed markdown data
*/
function parseMarkdownFile(params: {
filePath: string;
fileContent: string;
parseFrontMatter?: ParseFrontMatter;
removeContentTitle?: boolean;
}): Promise<{
frontMatter: { [key: string]: unknown };
contentTitle: string | undefined;
excerpt: string | undefined;
content: string;
}>;Usage Example:
import { parseMarkdownFile } from "@docusaurus/utils";
const markdownContent = `---
title: Getting Started
description: A guide to getting started
tags: [guide, intro]
---
# Welcome to the Guide
This is the introduction to our comprehensive guide.
## Installation
First, install the required dependencies...
`;
const result = await parseMarkdownFile({
filePath: "/docs/guide.md",
fileContent: markdownContent,
removeContentTitle: true,
});
console.log(result);
// Result: {
// frontMatter: { title: "Getting Started", description: "A guide...", tags: [...] },
// contentTitle: "Welcome to the Guide",
// excerpt: "This is the introduction to our comprehensive guide.",
// content: "This is the introduction...\n\n## Installation\n\nFirst, install..."
// }parseFileContentFrontMatterParses front matter using gray-matter with safe mutation handling.
/**
* Parses front matter using gray-matter with safe mutation handling
* @param fileContent - Raw file content with front matter
* @returns Object with parsed front matter and remaining content
*/
function parseFileContentFrontMatter(fileContent: string): {
frontMatter: { [key: string]: unknown };
content: string;
};parseMarkdownContentTitleExtracts title from markdown content (ATX or Setext style).
/**
* Extracts title from markdown content (ATX or Setext style)
* @param contentUntrimmed - Raw markdown content
* @param options - Parsing options
* @param options.removeContentTitle - Whether to remove title from content
* @returns Object with processed content and extracted title
*/
function parseMarkdownContentTitle(
contentUntrimmed: string,
options?: { removeContentTitle?: boolean }
): {
content: string;
contentTitle: string | undefined;
};createExcerptCreates excerpt from markdown content, ignoring headers, imports, and code blocks.
/**
* Creates excerpt from markdown content, ignoring headers, imports, and code blocks
* @param fileString - Markdown content to extract excerpt from
* @returns Excerpt string or undefined if no suitable content found
*/
function createExcerpt(fileString: string): string | undefined;parseMarkdownHeadingIdParses custom ID from markdown heading (e.g., "## Title {#id}").
/**
* Parses custom ID from markdown heading
* @param heading - Heading text to parse
* @returns Object with text and extracted ID
*/
function parseMarkdownHeadingId(heading: string): {
text: string;
id: string | undefined;
};writeMarkdownHeadingIdAdds heading IDs to markdown content, respecting existing IDs and avoiding collisions.
/**
* Adds heading IDs to markdown content
* @param content - Markdown content to process
* @param options - ID generation options
* @returns Markdown content with heading IDs added
*/
function writeMarkdownHeadingId(
content: string,
options?: WriteHeadingIDOptions
): string;escapeMarkdownHeadingIdsEscapes heading IDs for MDX 2 compatibility (adds backslashes to curly braces).
/**
* Escapes heading IDs for MDX 2 compatibility
* @param content - Markdown content to escape
* @returns Content with escaped heading IDs
*/
function escapeMarkdownHeadingIds(content: string): string;unwrapMdxCodeBlocksRemoves mdx-code-block wrappers for Crowdin compatibility.
/**
* Removes mdx-code-block wrappers for Crowdin compatibility
* @param content - Content with mdx-code-block wrappers
* @returns Content without wrappers
*/
function unwrapMdxCodeBlocks(content: string): string;admonitionTitleToDirectiveLabelConverts legacy ":::note Title" to ":::note[Title]" directive syntax.
/**
* Converts legacy admonition syntax to directive syntax
* @param content - Content with legacy admonition syntax
* @param admonitionContainerDirectives - Array of admonition directive names
* @returns Content with updated directive syntax
*/
function admonitionTitleToDirectiveLabel(
content: string,
admonitionContainerDirectives: string[]
): string;resolveMarkdownLinkPathnameResolves markdown link pathname to permalink, handling relative and absolute links.
/**
* Resolves markdown link pathname to permalink
* @param linkPathname - Link pathname to resolve
* @param context - Resolution context
* @param context.sourceFilePath - Path of the source file containing the link
* @param context.sourceToPermalink - Map of source paths to permalinks
* @param context.contentPaths - Content directory paths
* @param context.siteDir - Site root directory
* @returns Resolved permalink or null if cannot be resolved
*/
function resolveMarkdownLinkPathname(
linkPathname: string,
context: {
sourceFilePath: string;
sourceToPermalink: SourceToPermalink;
contentPaths: ContentPaths;
siteDir: string;
}
): string | null;Usage Examples:
import {
parseMarkdownHeadingId,
writeMarkdownHeadingId,
createExcerpt,
escapeMarkdownHeadingIds,
} from "@docusaurus/utils";
// Parse heading with custom ID
const heading = "## Getting Started {#start}";
const parsed = parseMarkdownHeadingId(heading);
// Result: { text: "Getting Started", id: "start" }
// Add heading IDs to content
const markdownWithoutIds = `
# Introduction
This is the intro.
## Getting Started
Let's begin.
### Installation
Install the package.
`;
const withIds = writeMarkdownHeadingId(markdownWithoutIds);
// Result: Content with auto-generated IDs like {#introduction}, {#getting-started}, etc.
// Create excerpt
const longContent = `# Title
This is the introduction paragraph that should become the excerpt.
## Section 1
More detailed content here...
\`\`\`javascript
// Code blocks are ignored
console.log("hello");
\`\`\`
`;
const excerpt = createExcerpt(longContent);
// Result: "This is the introduction paragraph that should become the excerpt."
// Escape for MDX 2
const withHeadingIds = "## Title {#custom-id}";
const escaped = escapeMarkdownHeadingIds(withHeadingIds);
// Result: "## Title \\{#custom-id\\}"