Skip to content

Commit

Permalink
Optimize sitemap generator
Browse files Browse the repository at this point in the history
  • Loading branch information
IgorKowalczyk committed Mar 6, 2023
1 parent 1c604d6 commit 045c5d9
Showing 1 changed file with 28 additions and 25 deletions.
53 changes: 28 additions & 25 deletions lib/scripts/generate-sitemap.mjs
Original file line number Diff line number Diff line change
@@ -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 = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${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 `<url>
<loc>https://igorkowalczyk.dev/${route}</loc>
<priority>${route ? "0.80" : "1"}</priority>
</url>
`;
</url>`;
})
.join("")}
</urlset>`;

writeFileSync(
await writeFile(
"public/sitemap.xml",
format(sitemap, {
parser: "html",
Expand Down

0 comments on commit 045c5d9

Please sign in to comment.