Automatically generate sitemap.xml in SvelteKit

Alex Schnabl
2 min readAug 13, 2023

For SEO a sitemap.xml is crucial, however manually creating one only once is already a very annoying task, which is even worst if your website get more and more pages often.

Required Packages

For this to work we will need to install some npm packages first:

npm install directory-tree

npm install typescript

npm install tsx

Sitemap Generator Script

In your project root, create a directory scripts with the file generate-sitemap.ts:

import dirTree from 'directory-tree';
import * as fs from "fs";

let baseRoute = "/";
let routes: string[] = [baseRoute]
let date = new Date().toISOString().split('T')[0]

function getSitemapXML(domain: string, routes: string[]) {
let sitemap = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
sitemap += "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"
routes.forEach(route => {
sitemap += getSitemapUrl(domain + route)
})
sitemap += "\n</urlset>"
return sitemap;
}

function getSitemapUrl(location: string) {
let url =
"<url>\n" +
`<loc>${location}</loc>\n` +
`<lastmod>${date}</lastmod>\n` +
"</url>";
return url
}

function getEndpoints(tree…

--

--

Alex Schnabl
Alex Schnabl

Written by Alex Schnabl

Entrepreneur & Software Developer

No responses yet