Hey everyone! While working on my website, I needed to generate a sitemap. I ended up creating a simple and easy-to-use solution in the form of an npm package—and I thought, why not share it with you all? This package makes it super easy to generate sitemaps for your website in Node.js. Whether you're building a small site or a large-scale application, this tool can help you get your sitemap up and running in no time.
In this post, I'll show you how to use the package and get started with generating sitemaps effortlessly. Let’s dive in!
To get started, you’ll first need to install the package using npm. Run the following command:
Shell
npm i ap-sitemap
Once the package is installed, you can create a sitemap instance. Simply require the package and configure it with your site’s details. Here's an example of how you can set it up:
JavaScript
const SiteMapGenerator = require('ap-sitemap');
const sitemap = new SiteMapGenerator({
baseUrl: 'https://yourwebsite.com', // Replace with your website's URL
outDir: 'dist', // Output directory for the sitemap (default is 'build')
limit: 50000, // Maximum number of URLs in the sitemap (default is 50,000)
removeIndexExtension: true, // Removes '/index.html' or other extensions from URLs
});
Next, you'll want to add pages to your sitemap. You can specify the URL, last update time, change frequency, and priority for each page. Here's an example of how you can add multiple pages:
JavaScript
sitemap.addPages([
{
url: 'https://example.com/page1',
updatedAt: '2024-11-04T10:00:00Z',
changefreq: 'daily',
priority: 1.0,
},
{
url: 'https://example.com/page2',
updatedAt: '2024-11-03T10:00:00Z',
changefreq: 'weekly',
priority: 0.8,
},
]);
Finally, you can generate your sitemap with a simple function call. This will create a sitemap.xml file in the output directory you specified (e.g., dist/
).
JavaScript
const sitemapUrl = generator.generate(); // https://yourwebsite.com/sitemap.xml