Describe the bug
robots.txt
isn't generated & siteUrl
isn't outputted properly while adding script to Next's compilation chain. In place of siteUrl
, it has undefined
everywhere. Even the exclude
property isn't working properly.
As mentioned in my previous issue #64, I wanted to use frontmatter
fields to generate Sitemap.
I found a way to do it by using Next's compilation chain.
Here's a short article on that → https://dev.to/nalanj/adding-scripts-to-next-js-n7i
TL;DR 👇
I put this in my next.config.js
:
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
module.exports = withBundleAnalyzer({
.
.
.
webpack: (config, options) => {
.
.
.
if (!options.dev && options.isServer) {
const originalEntry = config.entry
config.entry = async () => {
const entries = { ...(await originalEntry()) }
entries['./scripts/build-rss'] = './scripts/build-rss.js'
entries['./scripts/build-sitemap'] = './scripts/build-sitemap.js'
return entries
}
}
}
})
The build-sitemap.js
file gets compiled through Webpack using Next's compilation chain & gets outputted at .next/server/scripts/build-sitemap.js
My build-sitemap.js
file looks like:
import { getAllDraftEssays } from '@/utils/essay/getAllEssayPreviews'
import { getAllDraftTutorials } from '@/utils/tutorial/getAllTutorialPreviews'
const draftPosts = [...getAllDraftEssays(), ...getAllDraftTutorials()].map(
(p) => `/${p.slug}`
)
export default {
siteUrl: 'https://akshaykadam.com',
generateRobotsTxt: true,
sitemapSize: 7000,
exclude: draftPosts,
}
module.exports
wasn't working so I used export default
.
getAllDraftEssays
looks like:
export const getAllDraftEssays = (): Array<{
slug: string
module: any
}> =>
importAll(require.context('../../pages/essay/?rss', true, /\.mdx$/))
.filter((p: Post) => !p.module.meta.published)
.sort((a: Post, b: Post) => dateSortDesc(a.module.meta.date, b.module.meta.date))
Technically, this should output sitemap.xml
correctly & robots.txt
should be generated. I'm not sure why it isn't happening but would love to build it in my Next's compilation chain as it can generate Sitemap dynamically by using some frontmatter
fields like published
or draft
:)