Generate sitemap Angular SSR
Creating sitemap for a site that has pre-render support gets little tricky. I have been looking over docs to get some resources. But haven't found any. So I used a way that can help to get the sitemaps for a SSR site.
We would need to use two NPM packages:
At first we need to generate the static bundle from the script of Angular SSR.
From that we will have a dist
folder with static
HTML code.
We will use Glob module to fetch all the files in the dist/static
folder.
const { globSync } = require('glob');
const routes = globSync('./dist/static/**/*.html')
This will create an array with all the generated static code.
Now we can use this paths to create the sitemap.xml
using Sitemap module.
const { createWriteStream, readdirSync } = require('fs');
const { SitemapStream } = require('sitemap');
const sitemap = new SitemapStream({ hostname: 'https://example.com' });
const writeStream = createWriteStream('./sitemap.xml');
sitemap.pipe(writeStream);
sitemap.write({ url: '/', changefreq: 'weekly', priority: 0.9, lastmod: new Date().toDateString() });
sitemap.end();
Now finally we can generate the required sitemap using following:
for(var routeIndex = 0; routeIndex < routes.length; routeIndex++) {
const routeLink = routes[routeIndex]
.replace('dist/static', '')
.replace('index.html', '')
sitemap.write({ url: routeLink});
}