Last active
April 3, 2020 16:17
-
-
Save spemer/7f07e9adc25888f4af858d10c5818499 to your computer and use it in GitHub Desktop.
sitemap-common.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const globby = require("globby"); | |
const prettier = require("prettier"); | |
const getDate = new Date().toISOString(); | |
const YOUR_AWESOME_DOMAIN = "https://website.com"; | |
const formatted = sitemap => prettier.format(sitemap, { parser: "html" }); | |
(async () => { | |
const pages = await globby([ | |
// include | |
"../pages/**/*.tsx", | |
"../pages/*.tsx", | |
// exclude | |
"!../pages/_*.tsx" | |
]); | |
const pagesSitemap = ` | |
${pages | |
.map(page => { | |
const path = page | |
.replace("../pages/", "") | |
.replace(".tsx", "") | |
.replace(/\/index/g, ""); | |
const routePath = path === "index" ? "" : path; | |
return ` | |
<url> | |
<loc>${YOUR_AWESOME_DOMAIN}/${routePath}</loc> | |
<lastmod>${getDate}</lastmod> | |
</url> | |
`; | |
}) | |
.join("")} | |
`; | |
const generatedSitemap = ` | |
<?xml version="1.0" encoding="UTF-8"?> | |
<urlset | |
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" | |
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" | |
> | |
${pagesSitemap} | |
</urlset> | |
`; | |
const formattedSitemap = [formatted(generatedSitemap)]; | |
fs.writeFileSync("../public/sitemap-common.xml", formattedSitemap, "utf8"); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment