vite-sitemap
Version:
The plugin helps to automatically create a sitemap. A sitemap is like a map for search engines, telling them what pages you have on your site. This makes it easier for search engines to find website and urls!
58 lines (57 loc) • 2.27 kB
JavaScript
// import { adslash, unslash } from 'appmon/url';
import { format } from 'date-fns'; // For formatting the last modification date
import { writeFile } from "fs/promises";
import { resolve } from "path";
export const unslash = (str) => str.replace(/(\/$)|(^\/)/g, "");
/**
* add slash from last of url or string
* @param str
* @returns
*/
export const adslash = (str) => unslash(str).replace(/$/, "/");
export default function sitemap(options) {
const urls = (options === null || options === void 0 ? void 0 : options.urls) || [];
const baseUrl = (options === null || options === void 0 ? void 0 : options.baseURL) || "";
const filename = (options === null || options === void 0 ? void 0 : options.filename) || 'sitemap.xml';
const today = new Date();
const formattedDate = format(today, "yyyy-MM-dd'T'HH:mm:ss'Z'"); // Format the current date
const sitemapEntries = urls.map((route, i) => {
return `<url>
<loc>${adslash(baseUrl)}${unslash(route)}</loc>
<lastmod>${formattedDate}</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>`;
});
const sitemapXML = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"
xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1"
xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
<url>
<loc>${baseUrl}</loc>
<lastmod>${formattedDate}</lastmod>
<changefreq>daily</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>${adslash(baseUrl)}</loc>
<lastmod>${formattedDate}</lastmod>
<changefreq>daily</changefreq>
<priority>0.9</priority>
</url>
${sitemapEntries.join('')}
</urlset>
`;
return {
name: 'sitemap',
async writeBundle(options) {
try {
await writeFile(resolve(options.dir, filename), sitemapXML);
}
catch (error) {
throw new Error(String(error));
}
},
};
}
;