Skip to content

Instantly share code, notes, and snippets.

@a0s
Last active May 21, 2024 14:13
Show Gist options
  • Save a0s/a15f0d3dee14d5c4457dc2dc77657207 to your computer and use it in GitHub Desktop.
Save a0s/a15f0d3dee14d5c4457dc2dc77657207 to your computer and use it in GitHub Desktop.
The simplest sitemap.xml generation plugin for Vite/Vue with ability to have alternate links for languages
import fs from 'fs/promises';
import path from 'path';
import {type Plugin} from 'vite';
const supportedLanguages: { [code: string]: string } = {
'de': 'Deutsch',
'en': 'English',
'es': 'Español'
}
export interface SitemapOptionsRoutes {
[path: string]: Array<{ [key: string]: string }>;
}
function generateSitemap(obj: { baseUrl: string, routes: string[] }): Plugin {
const routes: SitemapOptionsRoutes = obj.routes.reduce<SitemapOptionsRoutes>((acc, route) => {
acc[route] = Object.keys(supportedLanguages).map(lang => {
const href = new URL(`${lang}${route}`, obj.baseUrl).toString();
return {hreflang: lang, href};
}).concat({hreflang: 'x-default', href: new URL(route, obj.baseUrl).toString()});
return acc;
}, {});
return {
name: 'yet-another-vite-plugin-sitemap',
apply: 'build',
async closeBundle() {
let sitemap = '<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml">\n';
for (const route in routes) {
if (routes.hasOwnProperty(route)) {
sitemap += ` <url>\n <loc>${new URL(route, obj.baseUrl).toString()}</loc>\n`;
routes[route].forEach(alt => {
const attributes = Object.keys(alt).map(key => `${key}="${alt[key]}"`).join(' ');
sitemap += ` <xhtml:link rel="alternate" ${attributes}/>\n`;
});
sitemap += ' </url>\n';
}
}
sitemap += '</urlset>';
const outputPath = path.resolve('dist', 'sitemap.xml');
await fs.mkdir(path.dirname(outputPath), {recursive: true});
await fs.writeFile(outputPath, sitemap);
},
};
}
export default generateSitemap;
export default defineConfig({
plugins: [
vue(),
generateSitemap({
baseUrl: `https://somesite.com`,
routes: [
"/",
"/page1",
"/page1",
],
}),
],
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment