From 0613a657a88e4229a6c5efd7d1ea790275009f6e Mon Sep 17 00:00:00 2001 From: Avraham Sakal Date: Sun, 10 Nov 2024 10:06:14 -0500 Subject: [PATCH] improve build-time tags collection * works better with types * works with Vite hot reload! --- src/Blog/SearchHeader/TagCloud/TagCloud.tsx | 12 ++++++- src/tags.ts | 16 ++++++++++ vite-plugin-tags.mjs | 35 --------------------- vite.config.ts | 7 +---- 4 files changed, 28 insertions(+), 42 deletions(-) create mode 100644 src/tags.ts delete mode 100644 vite-plugin-tags.mjs diff --git a/src/Blog/SearchHeader/TagCloud/TagCloud.tsx b/src/Blog/SearchHeader/TagCloud/TagCloud.tsx index 6b32f54..7558c37 100644 --- a/src/Blog/SearchHeader/TagCloud/TagCloud.tsx +++ b/src/Blog/SearchHeader/TagCloud/TagCloud.tsx @@ -1,5 +1,15 @@ import Box from "@mui/material/Box"; +import { tags } from "../../../tags.js"; export function TagCloud() { - return Tags; + return ( + + Tags + + + ); } diff --git a/src/tags.ts b/src/tags.ts new file mode 100644 index 0000000..3b7a9fb --- /dev/null +++ b/src/tags.ts @@ -0,0 +1,16 @@ +const modules = import.meta.glob>("./articles/*", { + import: "tags", + eager: true, +}); + +export const tags = Object.entries(modules).reduce( + (tagsSet, [modulePath, moduleTags]) => { + if (moduleTags) { + for (const tag of moduleTags) { + tagsSet.add(tag); + } + } + return tagsSet; + }, + new Set() +); diff --git a/vite-plugin-tags.mjs b/vite-plugin-tags.mjs deleted file mode 100644 index a659611..0000000 --- a/vite-plugin-tags.mjs +++ /dev/null @@ -1,35 +0,0 @@ -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()])};` - ); - }, - }; -} diff --git a/vite.config.ts b/vite.config.ts index a581511..c5fc99c 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,12 +1,7 @@ import { defineConfig } from "vite"; import preact from "@preact/preset-vite"; -// import tagsPlugin from "./vite-plugin-tags.mjs"; // https://vitejs.dev/config/ export default defineConfig({ - plugins: [ - preact(), - //@ ts-expect-error - // tagsPlugin(), - ], + plugins: [preact()], });