Files
gpx.studio/website/src/lib/sitemap.ts

43 lines
1.4 KiB
TypeScript
Raw Normal View History

2024-06-26 20:33:01 +02:00
import fs from 'fs';
2024-07-08 19:07:33 +02:00
import { glob } from 'glob';
import { languages } from '$lib/languages';
2024-06-26 20:33:01 +02:00
2024-09-30 11:04:20 +02:00
function getURLForLanguage(lang: string, path: string): string {
return `https://gpx.studio${lang === 'en' ? '' : `/${lang}`}${path}`;
}
2024-06-26 20:33:01 +02:00
function generateSitemap() {
2024-09-30 11:04:20 +02:00
const pages = glob.sync('**/*.html', { cwd: 'build' }).map((page) => `/${page}`);
2024-06-26 20:33:01 +02:00
2024-07-08 19:07:33 +02:00
let sitemap = '<?xml version="1.0" encoding="UTF-8"?>\n';
2024-07-08 19:17:03 +02:00
sitemap += '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n';
2024-07-08 19:07:33 +02:00
pages.forEach((page) => {
2024-09-30 11:04:20 +02:00
const path = page.replace('/index.html', '').replace('.html', '');
2024-07-08 19:07:33 +02:00
2024-09-30 11:04:20 +02:00
const rootDir = path.split('/')[1];
if (path.includes('embed') || path.includes('404') || languages[path] || languages[rootDir]) {
2024-07-08 19:07:33 +02:00
// Skip localized pages
return;
}
Object.keys(languages).forEach((language) => {
sitemap += `<url>\n`;
2024-09-30 11:04:20 +02:00
sitemap += ` <loc>${getURLForLanguage(language, path)}</loc>\n`;
2024-07-08 19:07:33 +02:00
Object.keys(languages).forEach((alternate) => {
if (alternate === language) return;
2024-09-30 11:04:20 +02:00
sitemap += ` <xhtml:link rel="alternate" hreflang="${alternate}" href="${getURLForLanguage(alternate, path)}" />\n`;
2024-07-08 19:07:33 +02:00
});
sitemap += `</url>\n`;
});
});
sitemap += '</urlset>';
return sitemap;
2024-06-26 20:33:01 +02:00
}
fs.writeFileSync('build/sitemap.xml', generateSitemap());