34 lines
1.2 KiB
JavaScript
34 lines
1.2 KiB
JavaScript
import 'dotenv/config';
|
|
import { getAllSlugs } from './data.js';
|
|
import fs from 'fs';
|
|
import path from 'path';
|
|
import { fileURLToPath } from 'url';
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = path.dirname(__filename);
|
|
|
|
async function generateSitemap() {
|
|
const slugs = await getAllSlugs();
|
|
const siteUrl = process.env.SITE_URL || 'https://yourdomain.com';
|
|
const urls = slugs.map(slugArr => {
|
|
if (slugArr.length === 1 && slugArr[0] === '/') {
|
|
return '/';
|
|
}
|
|
return '/' + slugArr.join('/');
|
|
});
|
|
|
|
let uniqueUrls = Array.from(new Set(urls));
|
|
if (!uniqueUrls.includes('/')) {
|
|
uniqueUrls.unshift('/');
|
|
} else {
|
|
uniqueUrls = uniqueUrls.filter(url => url !== '/');
|
|
uniqueUrls.unshift('/');
|
|
}
|
|
|
|
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${uniqueUrls.map(url => `\n <url>\n <loc>${siteUrl}${url}</loc>\n <changefreq>weekly</changefreq>\n <priority>0.7</priority>\n </url>`).join('')}\n</urlset>`;
|
|
const sitemapPath = path.resolve(__dirname, '../public/sitemap.xml');
|
|
fs.writeFileSync(sitemapPath, sitemap, 'utf8');
|
|
console.log('Sitemap generated!');
|
|
}
|
|
|
|
generateSitemap();
|