@emelie
To create a sitemap dynamically in Angular 12, you can use a library called ngx-sitemap-generator
.
Here are the steps to use this library:
That's it! Now, whenever you run your Angular app, the sitemap will be generated dynamically and the robots.txt
file will include the sitemap URL.
@emelie
Please note that the ngx-sitemap-generator library is specifically designed for server-side rendering (SSR) in Angular applications. If you are not using SSR, this library may not be suitable for your needs.
For more advanced and dynamic sitemap generation in Angular, you can follow these steps:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import { Injectable } from '@angular/core'; import { SitemapStream } from 'sitemap'; import { createWriteStream } from 'fs'; import { join } from 'path'; import { DOCUMENT, ɵgetDOM } from '@angular/common'; @Injectable({ providedIn: 'root' }) export class SitemapService { constructor(@Inject(DOCUMENT) private document: any) {} generateSitemap(): void { const smStream = new SitemapStream({ hostname: 'https://example.com' }); const path = join(this.document.location.origin, '/sitemap.xml'); const writeStream = createWriteStream(path); smStream.pipe(writeStream); // Add URLs to your dynamic routes smStream.write({ url: '/' }); smStream.write({ url: '/about' }); // Add more URLs as required smStream.end(); writeStream.on('finish', () => { console.log('Sitemap generated!'); }); } } |
This example shows how to generate a sitemap with two static routes (/
and /about
). You can add more routes as required.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import { Component } from '@angular/core'; import { SitemapService } from './sitemap.service'; @Component({ selector: 'app-root', template: '<h1>Hello, World!</h1>' }) export class AppComponent { constructor(private sitemapService: SitemapService) {} ngOnInit() { this.sitemapService.generateSitemap(); } } |
Remember to update your robots.txt
file to include the URL of the dynamic sitemap:
1
|
Sitemap: https://example.com/sitemap.xml |
By following these steps, you can generate a sitemap dynamically in Angular 12 without relying on external libraries.