From 045c5d9cb2083b6d989564eb8b111dd5430ef531 Mon Sep 17 00:00:00 2001 From: Igor Kowalczyk Date: Mon, 6 Mar 2023 19:40:56 +0100 Subject: [PATCH] Optimize sitemap generator --- lib/scripts/generate-sitemap.mjs | 53 +++++++++++++++++--------------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/lib/scripts/generate-sitemap.mjs b/lib/scripts/generate-sitemap.mjs index 6233f96bd..938f739c2 100644 --- a/lib/scripts/generate-sitemap.mjs +++ b/lib/scripts/generate-sitemap.mjs @@ -1,48 +1,51 @@ -import { writeFileSync } from "fs"; +/* eslint-disable no-undef */ +import { writeFile } from "fs/promises"; import { globby } from "globby"; import { allBlogs } from "../../.contentlayer/generated/index.mjs"; import { format } from "prettier"; import "dotenv/config"; +import path from "path"; -const pages = await globby([ - // prettier - "pages/*.{js,jsx,ts,tsx}", - "pages/*/*.{js,jsx,ts,tsx}", - "!pages/_*.js*", - "!pages/[*.jsx", - "!pages/api", - "!pages/404.js*", - "!pages/middleware.*", +const [pages, blogPages] = await Promise.all([ + globby([ + // Prettier + "app/**/*.{jsx,js}", + "!app/api/**/*", + "!app/{layout,loading,error}.{jsx,js,ts,tsx}", + "!app/blog/**/*", + ]), + Promise.resolve(allBlogs).then((blogs) => blogs.map((blog) => `app/blog/${blog.slug}`)), ]); -const blogPages = allBlogs.map((page) => `pages/blog/${page.slug}`); const sitemap = ` ${pages .concat(blogPages) .map((page) => { - if (page.includes("[")) return; - console.log(`Found: ${page.split(".")[0]} as a page`); - const path = page - .split("/") - .map((path) => path.split(".")[0]) - .slice(1) - .join("/") - .replace(/\/index$/, "") - .replace("pages/", "/") - .replace("public/", "/") + console.log(`Found: ${page} as a page`); + const parsedPath = path.parse(page); + const dirPath = parsedPath.dir + .replace(/^app\//, "") + .replace(/\/page$/, "") .replace("/rss.xml", ""); - const route = path === "index" ? "" : path; + const fileName = parsedPath.name === "page" ? "" : parsedPath.name; + let filePath = path.join(dirPath, fileName); + if (filePath.startsWith("app/")) { + filePath = filePath.substring(4); + } + if (filePath.endsWith("/page")) { + filePath = filePath.substring(0, filePath.length - 5); + } + const route = filePath === "" ? "" : filePath; return ` https://igorkowalczyk.dev/${route} ${route ? "0.80" : "1"} - - `; + `; }) .join("")} `; -writeFileSync( +await writeFile( "public/sitemap.xml", format(sitemap, { parser: "html",