Automatic Site Maps in Svelte
Autogenerate a sitemap
Let's update our sitemap generation code to produce clean URLs without the "/src/routes" prefix:
Let's break down the changes and explain how this solves the problem:
We import the
relative
function from thepath
module. This will help us get the relative path from the base directory to each route.In the
getRoutes
function:We define
baseDir
as the absolute path to the 'src/routes' directory.We use a nested
traverse
function to recursively go through the directories.For each '+page.svelte' file, we calculate the route by getting the relative path from
baseDir
to the current directory.We replace backslashes with forward slashes to ensure consistent URL formatting.
We handle the root route ('/') separately by checking if the relative path is '.'.
We've removed any hardcoded 'src/routes' parts from the URL generation process.
This improved version should generate clean URLs for your sitemap, like:
Handling Dynamic Content
If you need to include dynamic content, you can still add it as before:
Automating Updates
To keep your sitemap up-to-date, consider these options:
Generate the sitemap during the build process.
Use a serverless function to regenerate the sitemap periodically.
Trigger sitemap regeneration when content is updated.
For example, add a build script to your package.json
:
Then create a generate-sitemap.js
file that uses this logic to create a static sitemap.xml file during builds.
By implementing these improvements, you'll have a robust, automated sitemap generation system for your SvelteKit project that produces clean URLs without the "/src/routes" prefix, ensuring search engines always have the most up-to-date and accurate information about your site structure.
Citations: [1] https://example.com/src/routes/testpage
Last updated