気まぐれ更新ブログ
Nuxt.jsでサイトマップを作るモジュールといえば@nuxtjs/sitemap
が有名ですが、@nuxt/content
で作られた動的なページはうまくルーティングされないようでデフォルトの設定では正しいサイトマップが作れません。そこで、ルーティングの設定をいじって動的なページを認識させます。
NuxtJS 2.14.0
@nuxt/content 1.7.0
@nuxtjs/sitemap 2.4.0
ファイル構造
content
└─ articles
└─ hello.md
pages
├─ articles
│ └─ _slug.vue
│
└─ index.vue
まずは@nuxtjs/sitemapをインストールしましょう。
npm install @nuxtjs/sitemap
もしくは
yarn add @nuxtjs/sitemap
でインストールできます。
nuxt.config.jsのmoduleに、@nuxtjs/sitemapを追加し、hostnameを設定します。hostnameには、自分のサイトのURLを設定します。
modules: [
'@nuxtjs/sitemap'
],
sitemap: {
hostname: 'https://YOUR_SITE.example'
}
ここまででサイトマップを生成することが可能になりますが、nuxt generate
して生成されたdist/sitemap.xml
を見るとarticles以下の記述がありません。
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
<url>
<loc>https://your_site.example/</loc>
</url>
</urlset>
sitemap: {
hostname: 'https://YOUR_SITE.example',
routes: async () => {
const { $content } = require('@nuxt/content')
const articles = await $content('articles').only(['path']).fetch()
return articles.map(article => article.path)
}
}
routes
で、content/articles
に保存された全ページを取得し、pathを返すようにします。こうすることで、@nuxt/contentで作成されたページをサイトマップに反映させることができます。
articles以外のフォルダ、例えばcontent/posts
のページを取得する場合は$content('articles')
を$content('posts')
に変更するなど、ご自身の環境に合わせてください。
ここまでの設定で、もう一度nuxt generate
をすると、以下のように/articles/hello
が追加されているのがわかります。
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
<url>
<loc>https://your_site.example/articles/hello</loc>
</url>
<url>
<loc>https://your_site.example/</loc>
</url>
</urlset>
本当は自動でルーティングしてくれると嬉しいんですが、ひと手間かけることでsitemap.xmlにnuxt/contentのページを追加することができますので、ぜひお試しください。