Pretty Sitemaps With Gatsby-Plugin-Sitemap
Why are sitemaps by gatsby-plugin-sitemap ugly?
In short, because gatsby-plugin-sitemap only outputs raw XML. This might be okay if you don’t need to fiddle with your sitemap more than once a year or do not have a marketing team to please.
In my case, I have marketing people to please and this:
won’t cut it.
gatsby-plugin-advanced-sitemap would’ve been perfect, but it doesn’t support multilingual sitemaps. (At least not the way I want it to.)
The workaround I found is simply to…
Add an XSL style sheet to the sitemap generated by Gatsby
XSL is basically CSS for XML. All you need to make an XML sitemap pretty is give it a style sheet.
So, find a style sheet that suits your need and put it in the ./static/
folder at
the root of your project. (I used a fantastic XSL stylesheet by Pedro Borges. Thank you, Pedro! )
Then, link to that stylesheet in the XML files generated by gatsby-plugin-sitemap. There is no out-of-the-box API to do this, but we can modify the XML files after the build has completed.
(Yes, this is the hacky part.)
// inside gatsby-node.js
const fs = require("fs");
// ...
exports.onPostBuild = () => {
fs.readdir("./public/sitemap/", (err, files) => {
files.forEach((file) => {
fs.readFile(`./public/sitemap/${file}`, "utf-8", (err, data) => {
const newValue = data.replace(
`<?xml version="1.0" encoding="UTF-8"?>`,
`<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="/sitemap.xsl"?>`
);
fs.writeFileSync(`./public/sitemap/${file}`, newValue, "utf-8");
});
});
});
};
onPostBuild
is provided by Gatsby. Since we know the sitemaps are generated
in the ./public/sitemap/
folder, all we need to do is:
- Iterate over each file in
./public/sitemap/
- Add
<?xml-stylesheet type="text/xsl" href="/sitemap.xsl"?>
to those files. (Assuming your style sheet is at./static/sitemap.xsl
) - Profit.
<?xml version="1.0" encoding="UTF-8"?>
is unlikely to change so I feel like
this strategy is pretty solid even though it’s not super duper clean.
Now, look how cute my sitemap is! ❤️
Happy hacking!