angular - generate sitemap.xml from @angular/router
Asked Answered
A

2

6

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 ?

Aerate answered 31/5, 2021 at 14:26 Comment(0)
M
3

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"
}
Mata answered 11/6, 2022 at 22:47 Comment(2)
I've been using it in production for some time now, works wellMata
I don't get it to work. I have imports from my Angular files. Error [ERR_REQUIRE_ESM]: require() of ES Module ...\node_modules\@angular\core\fesm2015\core.mjs not supported. Instead change the require of ...\node_modules\@angular\core\fesm2015\core.mjs to a dynamic import() which is available in all CommonJS modules.Zonate
M
2

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.

Melodimelodia answered 10/6, 2022 at 14:4 Comment(1)
thank you for this post let me check if this reply to my needAerate

© 2022 - 2024 — McMap. All rights reserved.