Files
minhtran_dev/build-helpers/blogPostsPlugin.ts

37 lines
1.0 KiB
TypeScript
Raw Permalink Normal View History

2025-01-23 11:16:33 -05:00
import type { Plugin } from "vite";
import { resolve, join } from "node:path";
2025-12-31 18:23:28 -05:00
import { readdirSync, readFileSync, writeFileSync } from "node:fs";
import matter from "gray-matter";
2025-01-23 11:16:33 -05:00
2025-12-31 18:23:28 -05:00
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"))
2025-01-23 11:16:33 -05:00
.map((file) => {
2025-12-31 18:23:28 -05:00
const content = readFileSync(join(BLOG_DIR, file), "utf-8");
const { data } = matter(content);
return { ...data, slug: file.replace(".mdx", "") };
2025-01-23 11:16:33 -05:00
})
2025-12-31 18:23:28 -05:00
.sort(
(a, b) =>
new Date(b.date as string).getTime() -
new Date(a.date as string).getTime(),
);
2025-01-23 11:16:33 -05:00
2025-12-31 18:23:28 -05:00
writeFileSync(OUTPUT_FILE, JSON.stringify(posts, null, 2));
}
2025-01-23 11:16:33 -05:00
2025-12-31 18:23:28 -05:00
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();
}
});
},
});