Created
October 23, 2025 08:38
-
-
Save noxify/89a57ed90a283270df73f535960b68b5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Codemod: Convert YAML frontmatter in MDX files to export const metadata | |
| // Usage: node codemod-frontmatter-to-metadata.mjs | |
| // This script scans all MDX files in the content directory, extracts YAML frontmatter, | |
| // and converts it into a JavaScript export named `metadata`. | |
| // Dependencies: tinyglobby, js-yaml | |
| // Install them via: `pnpm add -D tinyglobby js-yaml` | |
| import fs from "fs" | |
| import path from "path" | |
| import yaml from "js-yaml" | |
| import { glob } from "tinyglobby" | |
| const CONTENT_DIR = path.join( | |
| path.dirname(new URL(import.meta.url).pathname), | |
| "../content", | |
| ) | |
| function parseFrontmatter(content) { | |
| const match = content.match(/^---([\s\S]*?)---\n?/) | |
| if (!match) return null | |
| try { | |
| return yaml.load(match[1]) | |
| } catch (e) { | |
| return null | |
| } | |
| } | |
| function removeFrontmatter(content) { | |
| return content.replace(/^---([\s\S]*?)---\n?/, "") | |
| } | |
| function metadataBlock(obj) { | |
| const entries = Object.entries(obj) | |
| .map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`) | |
| .join(",\n") | |
| return `export const metadata = {\n${entries}\n}\n\n` | |
| } | |
| async function run() { | |
| const files = await glob(`${CONTENT_DIR}/**/*.mdx`) | |
| for (const file of files) { | |
| const raw = fs.readFileSync(file, "utf8") | |
| const meta = parseFrontmatter(raw) | |
| if (!meta) continue | |
| const rest = removeFrontmatter(raw) | |
| const newContent = metadataBlock(meta) + rest.trimStart() | |
| fs.writeFileSync(file, newContent) | |
| console.log("Updated:", file) | |
| } | |
| } | |
| run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment