import type { Plugin } from "vite"; import { resolve, join } from "node:path"; import { readdirSync, readFileSync, writeFileSync } from "node:fs"; import matter from "gray-matter"; const BLOG_DIR = resolve("src/routes/blog"); const OUTPUT_FILE = resolve("src/data/posts.json"); function generatePostsJson() { const posts = readdirSync(BLOG_DIR) .filter((file) => file.endsWith(".mdx")) .map((file) => { const content = readFileSync(join(BLOG_DIR, file), "utf-8"); const { data } = matter(content); return { ...data, slug: file.replace(".mdx", "") }; }) .sort( (a, b) => new Date(b.date as string).getTime() - new Date(a.date as string).getTime(), ); writeFileSync(OUTPUT_FILE, JSON.stringify(posts, null, 2)); } export const blogPostsPlugin = (): Plugin => ({ name: "blog-posts-gen", buildStart: generatePostsJson, configureServer(server) { server.watcher.on("change", (path) => { if (path.includes("src/routes/blog") && path.endsWith(".mdx")) { generatePostsJson(); } }); }, });