Convert .md files to .mdx and add frontmatter
Rename the file
Add frontmatter at the top
npm install gray-matter fs-extranode 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); | |
| } |