Skip to content

Instantly share code, notes, and snippets.

@xmlking
Created December 27, 2025 19:32
Show Gist options
  • Select an option

  • Save xmlking/a784c3138f034bb391cd87713e2b1736 to your computer and use it in GitHub Desktop.

Select an option

Save xmlking/a784c3138f034bb391cd87713e2b1736 to your computer and use it in GitHub Desktop.
convert md to mdx and add frontmatter

Convert .md files to .mdx and add frontmatter Rename the file Add frontmatter at the top

npm install gray-matter fs-extra
node scripts/convert-md-to-mdx.js
// scripts/convert-md-to-mdx.js
import fs from "fs";
import path from "path";
import matter from "gray-matter";
const INPUT_DIR = "./content/md";
const OUTPUT_DIR = "./content/mdx";
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
function extractTitleFromContent(content) {
// match first H1: "# Title"
const match = content.match(/^#\s+(.+)\s*$/m);
return match ? match[1].trim() : null;
}
function removeFirstH1(content) {
return content.replace(/^#\s+.+\s*\n+/m, "");
}
for (const file of fs.readdirSync(INPUT_DIR)) {
if (!file.endsWith(".md")) continue;
const inputPath = path.join(INPUT_DIR, file);
const raw = fs.readFileSync(inputPath, "utf8");
const parsed = matter(raw);
const filenameSlug = file.replace(/\.md$/, "");
const headingTitle = extractTitleFromContent(parsed.content);
const title =
parsed.data.title ??
headingTitle ??
filenameSlug;
const description =
parsed.data.description ?? "";
const finalContent =
parsed.data.title
? parsed.content
: headingTitle
? removeFirstH1(parsed.content)
: parsed.content;
const frontmatter = {
...parsed.data, // preserve all existing fields
title,
description,
date: parsed.data.date ?? new Date().toISOString(),
};
const mdx = matter.stringify(finalContent, frontmatter);
const outputFile = file.replace(".md", ".mdx");
fs.writeFileSync(path.join(OUTPUT_DIR, outputFile), mdx);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment