@alauda/doom
Version:
Doctor Doom making docs.
52 lines (51 loc) • 1.94 kB
JavaScript
// based on https://github.com/jl917/rspress-plugin-sitemap/blob/master/src/index.ts
import fs from 'node:fs';
import { dirname } from 'node:path';
import { logger } from '@rspress/core';
const generateNode = (sitemap) => {
let result = '<url>';
for (const [tag, value] of Object.entries(sitemap)) {
result += `<${tag}>${value}</${tag}>`;
}
result += '</url>';
return result;
};
const generateXml = (sitemaps) => {
logger.log(`Generate sitemap.xml for ${sitemaps.length} pages.`);
return `<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">${sitemaps.reduce((node, sitemap) => node + generateNode(sitemap), '')}</urlset>`;
};
export function sitemapPlugin(options) {
options = {
domain: 'https://rspress.dev',
customMaps: {},
defaultChangeFreq: 'monthly',
defaultPriority: '0.5',
...options,
};
const sitemaps = [];
const set = new Set();
return {
name: 'rspress-plugin-sitemap',
extendPageData(pageData, isProd) {
if (!isProd || set.has(pageData.routePath)) {
return;
}
set.add(pageData.routePath);
sitemaps.push({
loc: `${options.domain}${pageData.routePath}`,
lastmod: fs.statSync(pageData._filepath).mtime.toISOString(),
priority: pageData.routePath === '/' ? '1.0' : options.defaultPriority,
changefreq: options.defaultChangeFreq,
...options.customMaps?.[pageData.routePath],
});
},
afterBuild(config, isProd) {
if (!isProd) {
return;
}
const outputPath = `${config.outDir || 'doc_build'}/sitemap.xml`;
fs.mkdirSync(dirname(outputPath), { recursive: true });
fs.writeFileSync(outputPath, generateXml(sitemaps));
},
};
}