tailwind-nextjs-blog/scripts/generate-sitemap.js

70 lines
2.1 KiB
JavaScript
Raw Permalink Normal View History

2022-10-17 23:37:01 +08:00
const fs = require('fs');
const globby = require('globby');
const matter = require('gray-matter');
const prettier = require('prettier');
const siteMetadata = require('../data/siteMetadata');
2022-07-17 21:40:41 +08:00
2022-10-17 23:37:01 +08:00
(async () => {
const prettierConfig = await prettier.resolveConfig('./.prettierrc.js');
2022-07-17 21:40:41 +08:00
const pages = await globby([
'pages/*.js',
'pages/*.tsx',
'data/blog/**/*.mdx',
'data/blog/**/*.md',
'public/tags/**/*.xml',
'!pages/_*.js',
'!pages/_*.tsx',
'!pages/api',
2022-10-17 23:37:01 +08:00
]);
2022-07-17 21:40:41 +08:00
const sitemap = `
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
${pages
.map((page) => {
// Exclude drafts from the sitemap
if (page.search('.md') >= 1 && fs.existsSync(page)) {
2022-10-17 23:37:01 +08:00
const source = fs.readFileSync(page, 'utf8');
const fm = matter(source);
2022-07-17 21:40:41 +08:00
if (fm.data.draft) {
2022-10-17 23:37:01 +08:00
return;
2022-07-17 21:40:41 +08:00
}
if (fm.data.canonicalUrl) {
2022-10-17 23:37:01 +08:00
return;
2022-07-17 21:40:41 +08:00
}
}
const path = page
.replace('pages/', '/')
.replace('data/blog', '/blog')
.replace('public/', '/')
.replace('.js', '')
.replace('.tsx', '')
.replace('.mdx', '')
.replace('.md', '')
2022-10-17 23:37:01 +08:00
.replace('/feed.xml', '');
const route = path === '/index' ? '' : path;
if (
page.search('pages/404.') > -1 ||
page.search(`pages/blog/[...slug].`) > -1
) {
return;
2022-07-17 21:40:41 +08:00
}
return `
<url>
<loc>${siteMetadata.siteUrl}${route}</loc>
</url>
2022-10-17 23:37:01 +08:00
`;
2022-07-17 21:40:41 +08:00
})
.join('')}
</urlset>
2022-10-17 23:37:01 +08:00
`;
2022-07-17 21:40:41 +08:00
const formatted = prettier.format(sitemap, {
...prettierConfig,
parser: 'html',
2022-10-17 23:37:01 +08:00
});
2022-07-17 21:40:41 +08:00
// eslint-disable-next-line no-sync
2022-10-17 23:37:01 +08:00
fs.writeFileSync('public/sitemap.xml', formatted);
})();