1 |
const { glob } = require("glob"); |
2 |
const { writeFileSync, lstatSync } = require("fs"); |
3 |
const path = require("path"); |
4 |
|
5 |
async function main() { |
6 |
const excluded = []; |
7 |
const pages = await glob("app/**/page.{tsx,md,mdx}"); |
8 |
const routes = []; |
9 |
|
10 |
for (const page of pages) { |
11 |
let route = page |
12 |
.replace(/[\/\\]\([a-z0-9A-Z_-]+\)/gi, "") |
13 |
.replace(/^app[\/\\]/gi, "") |
14 |
.replace(/[\/\\]page\.(ts|md)x/gi, "") |
15 |
.replace(/\\/g, "/"); |
16 |
|
17 |
route = |
18 |
route === "" || |
19 |
route === "page.tsx" || |
20 |
route === "page.mdx" || |
21 |
route === "page.md" |
22 |
? "/" |
23 |
: `/${route}`; |
24 |
|
25 |
if (excluded.includes(route)) { |
26 |
continue; |
27 |
} |
28 |
|
29 |
const lastmod = lstatSync(page).mtime; |
30 |
|
31 |
routes.push({ |
32 |
path: route, |
33 |
file: page.replace(/\\/g, "/"), |
34 |
lastmod, |
35 |
}); |
36 |
} |
37 |
|
38 |
const urls = routes.map( |
39 |
route => |
40 |
"\t" + |
41 |
` |
42 |
<url> |
43 |
<loc>${route.path}</loc> |
44 |
<lastmod>${route.lastmod.toISOString()}</lastmod> |
45 |
<priority>${route.path === "/" ? "1.0" : "0.8"}</priority> |
46 |
</url>`.trim(), |
47 |
); |
48 |
|
49 |
const urlset = ` |
50 |
<?xml version="1.0" encoding="UTF-8"?> |
51 |
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> |
52 |
${urls.join("\n")} |
53 |
</urlset> |
54 |
`.trim(); |
55 |
|
56 |
const json = JSON.stringify( |
57 |
routes.map(route => ({ |
58 |
loc: route.path, |
59 |
lastmod: route.lastmod.toISOString(), |
60 |
priority: route.path === "/" ? 1.0 : 0.8, |
61 |
})), |
62 |
); |
63 |
|
64 |
writeFileSync(path.join(__dirname, "sitemap.xml"), urlset); |
65 |
writeFileSync(path.join(__dirname, "sitemap.json"), json); |
66 |
} |
67 |
|
68 |
main(); |