jeremy-denis
jeremy-denis

Reputation: 6878

angular - generate sitemap.xml from @angular/router

I have an angular application with a small routing file like following

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'home',
    loadChildren: () => import('./pages/common/home/home.module').then( m => m.HomePageModule)
  },
  {
    path: 'contact',
    loadChildren: () => import('./pages/contact/contact.module').then( m => m.ContactPageModule)
  },
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Is there a mean to generate file sitemap.xml containing both url contact and home when building the application ?

Upvotes: 6

Views: 3792

Answers (2)

Ryan Eghrari
Ryan Eghrari

Reputation: 124

You can import your routes into sitemap.ts making sure to add a data object to each route with loc, lastmod, changefreq and priority.

export const routes: Routes = [
  {
    path: "",
    component: LandingComponent,
    data: {
      loc: "/",
      lastmod: "2022-04-07",
      changefreq: "daily",
      priority: "1.0",

and then

import * as fs from "fs";
import * as path from "path";

const HOSTNAME = "your-url-goes-here"
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`
  .concat(
    routes
      .map((route) =>
        createUrl(
          `${HOSTNAME}${route.data.loc}`,
          route.data.lastmod,
          route.data.changefreq,
          route.data.priority
        )
      )
      .join("\n")
  )
  )
  .concat("\n</urlset>");

fs.writeFileSync(path.join(__dirname, "./src/sitemap.xml"), sitemap);

Then you can add sitemap.ts to your package.json

...
"build-sitemap": "ts-node -O '{\"module\": \"commonjs\"}' ./sitemap.ts"
}

Upvotes: 3

Haris Bouchlis
Haris Bouchlis

Reputation: 2566

There is a tool that claims to do what you ask: https://github.com/Comcast/sitemapper-for-js

Follow the instructions in this article to set it up.

Hope it helps.

Upvotes: 2

Related Questions