You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
blog/vite-plugin-tags.mjs

36 lines
1011 B
JavaScript

import fs from "node:fs";
import path from "node:path";
import { tsImport } from "tsx/esm/api";
export default function tagsPlugin() {
return {
name: "tags-plugin",
enforce: "post",
async buildStart() {
const articlesDir = path.resolve(process.cwd(), "src/articles");
const allTags = new Set();
for (const file of fs.readdirSync(articlesDir)) {
const filePath = path.join(articlesDir, file);
if (filePath.endsWith(".tsx") || filePath.endsWith(".ts")) {
try {
const module = await tsImport(filePath, import.meta.url);
if (module.tags) {
for (const tag of module.tags) {
allTags.add(tag);
}
}
} catch (e) {
console.error(`Error importing ${file}:`, e);
}
}
}
fs.writeFileSync(
path.resolve(process.cwd(), "tags.js"),
`export const tags = ${JSON.stringify([...allTags.values()])};`
);
},
};
}