-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsitemap.plugin.ts
More file actions
74 lines (66 loc) · 2.29 KB
/
Copy pathsitemap.plugin.ts
File metadata and controls
74 lines (66 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import type {Plugin} from 'vite';
import {gitDate, siteRoutes} from './plugin-utils.ts';
/**
* Emits `sitemap.xml` and `robots.txt` into the client build output.
*
* Routes come from `siteRoutes` in plugin-utils, the same list the build
* prerenders: `src/app/pages/*.page.ts`, `src/content/**\/*.md` and the API
* symbol pages, minus `noIndex` pages. Each file's last commit date via
* `git log -1 --format=%cs` populates `<lastmod>`, falling back to mtime
* for uncommitted files.
*
* Versioning is per-deployment (each docs version is its own site under the
* adev / PrimeNG model), so there are no in-repo version variants to
* special-case here — the sitemap simply covers this deployment's content.
*
* `robots.txt` is a one-liner pointing at the sitemap.
*/
function escapeXml(s: string): string {
return s
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
export function sitemapPlugin(opts: {siteUrl: string}): Plugin {
let root = process.cwd();
const siteUrl = opts.siteUrl.replace(/\/+$/, '');
const today = () => new Date().toISOString().slice(0, 10);
return {
name: 'ngmd-sitemap',
apply: 'build',
configResolved(cfg) {
root = cfg.root;
},
generateBundle() {
const entries = new Map<string, string>();
for (const {route, file, noIndex} of siteRoutes(root)) {
if (!noIndex) entries.set(route, gitDate(file, root, today));
}
const urls = [...entries.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.map(([route, lastmod]) => {
const loc = escapeXml(`${siteUrl}${encodeURI(route)}`);
return ` <url>\n <loc>${loc}</loc>\n <lastmod>${lastmod}</lastmod>\n </url>`;
})
.join('\n');
const sitemap =
'<?xml version="1.0" encoding="UTF-8"?>\n' +
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n' +
urls +
'\n</urlset>\n';
this.emitFile({
type: 'asset',
fileName: 'sitemap.xml',
source: sitemap,
});
const robots = `User-agent: *\nAllow: /\nSitemap: ${siteUrl}/sitemap.xml\n`;
this.emitFile({
type: 'asset',
fileName: 'robots.txt',
source: robots,
});
},
};
}