Skip to content

Instantly share code, notes, and snippets.

@nsantos16
Last active Mar 25, 2021
Embed
What would you like to do?
Sitemap generator that I use for my personal site
// Check https://santosnicolas.com/notes/sitemap-next-js blog!
const fs = require("fs")
const globby = require("globby")
const prettier = require("prettier")
const siteMetadata = require("../data/siteMetadata")
;(async () => {
console.info("Generating Sitemap🗺")
const prettierConfig = await prettier.resolveConfig("./.prettierrc.js")
const pages = await globby(["pages/*.tsx", "data/**/*.mdx", "!pages/_*.tsx"])
const sitemap = `
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${pages
.map((page) => {
const path = page
.replace("pages/", "/")
.replace("data/blog", "/blog")
.replace("data/notes", "/notes")
.replace("public/", "/")
.replace(".tsx", "")
.replace(".mdx", "")
.replace("/index.xml", "")
const route = path === "/index" ? "" : path
return `
<url>
<loc>${`${siteMetadata.siteUrl}${route}`}</loc>
</url>
`
})
.join("")}
</urlset>
`
const formatted = prettier.format(sitemap, {
...prettierConfig,
parser: "html",
})
// eslint-disable-next-line no-sync
fs.writeFileSync("public/sitemap.xml", formatted)
console.info("Success generation of sitemap 🎉")
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment