nuxt-community / sitemap-module

Sitemap Module for Nuxt 2
https://sitemap.nuxtjs.org
MIT License
689 stars 127 forks source link

`sitemap.sitemaps`'s misses changes made to `sitemap.routes` by a generator #214

Open olets opened 3 years ago

olets commented 3 years ago

Expectation

If I hook into generate to change sitemap.routes, those changes are reflected in the sitemaps generated by the module.

Actual

If I hook into generate to change sitemap.routes, those changes are reflected in the sitemap-module output if the module is configured to output a single sitemap but not if the module is configured to output multiple sitemaps.

Details

I'm hooking into generate to add generated routes to the sitemap routes. Essentially:

// modules/sitemapRoutesGenerator

const sitemapRoutesGenerator = function () {
  this.nuxt.hook('generate:done', async context => {
    this.nuxt.options.sitemap.routes = // … something using await Array.from(context.generatedRoutes) …
  })
}

export default sitemapRoutesGenerator
// nuxt config
buildModules: [
  '@/modules/sitemapRoutesGenerator',
],

modules: [
  '@nuxtjs/sitemap',
],

(h/t https://dev.to/andynoir/sitemap-for-dynamic-routes-in-nuxtjs-4b96 for the general idea)

That works with a single sitemap:

// nuxt config
sitemap: {
  hostname: 'https://myhost.com',
}

The sitemap.xml generated when I run yarn generate reflects the routes as set in the generator.

But it doesn't work with multiple sitemaps:

sitemap: {
  hostname: 'multiple',
  sitemaps: [
    {
      hostname: 'https://myhost1.com',
      path: '/sitemap1.xml',
    },
    {
      hostname: 'https://myhost2.com',
      path: '/sitemap2.xml',
    }
  ],
}

The sitemap1.xml and sitemap2.xml generated when I run yarn generate are the same as they would be if I removed my custom generator.

olets commented 3 years ago

PS furthermore my expectation is that filter() in each sitemap would operate on the modified routes. I think the above is the only piece missing, but I suppose there could be a solution for the routes without filtering that doesn't still work with filtering:

sitemap: {
  hostname: 'multiple',
  sitemaps: [
    {
      hostname: 'https://myhost1.com',
      path: '/sitemap1.xml',
      filter ({ routes }) {
        return routes.filter(r => sitemap1Filter(r))
      },
    },
    {
      hostname: 'https://myhost2.com',
      path: '/sitemap2.xml',
      filter ({ routes }) {
        return routes.filter(r => sitemap2Filter(r))
      },
    }
  ],
}

would in my expectation use the generator-modified routes.

olets commented 3 years ago

Create an example repo:

Working with single sitemap https://github.com/olets/nuxt-sitemap-generator-issue-demos/tree/nuxt-community/sitemap-module/issues/214/single-sitemap

Not working with multiple sitemaps https://github.com/olets/nuxt-sitemap-generator-issue-demos/tree/nuxt-community/sitemap-module/issues/214/multiple-sitemaps

Clone, yarn, yarn generate