Skip to content

Instantly share code, notes, and snippets.

@delucis
Created December 2, 2022 23:45
Show Gist options
  • Save delucis/20ce3f4981235d968ae3440eadb11808 to your computer and use it in GitHub Desktop.
Save delucis/20ce3f4981235d968ae3440eadb11808 to your computer and use it in GitHub Desktop.
Migrate Astro-Flavored Markdown files to MDX

This script is a quick way to migrate existing Astro-flavoured Markdown pages in an Astro project to MDX pages.

It does the following:

  1. Loads all *.md files in your src/pages/ directory
  2. Parses each page’s frontmatter
  3. Moves the contents of setup in frontmatter into the main file body as required for imports in MDX
  4. Writes the updated contents of each page to the same location but as .mdx instead of .md
  5. Deletes the original .md file

You can run the script from your project route using Node:

node ./md2mdx.mjs
import glob from 'fast-glob';
import { readFileSync, rmSync, writeFileSync } from 'fs';
import matter from 'gray-matter';
async function migrate() {
const mdPages = await glob('./src/pages/**/*.md');
for (const path of mdPages) {
const fileContents = readFileSync(path, 'utf-8');
const file = matter(fileContents);
if (file.data.setup) {
const imports = file.data.setup
.split('\n')
.map((ln) => ln.trim())
.join('\n');
delete file.data.setup;
file.content = imports + '\n\n' + file.content;
}
const newFile = matter.stringify(file);
const newPath = path + 'x';
writeFileSync(newPath, newFile, 'utf-8');
rmSync(path);
}
}
migrate();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment