NineBolt

気まぐれ更新ブログ

@nuxt/contentで作成したページを含めたサイトマップを生成する

/thumbnails/nuxt-content-sitemap.png
共有する:

この記事では、@nuxtjs/sitemapで生成されるサイトマップに、@nuxt/contentで作成したページを含める方法を紹介します。

@nuxtjs/sitemapでサイトマップを作りたい

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のインストール

まずは@nuxtjs/sitemapをインストールしましょう。

npm install @nuxtjs/sitemap

もしくは

yarn add @nuxtjs/sitemap

でインストールできます。

@nuxtjs/sitemapの設定

nuxt.config.jsのmoduleに、@nuxtjs/sitemapを追加し、hostnameを設定します。hostnameには、自分のサイトのURLを設定します。

例: https://ninebolt.net

nuxt.config.js
modules: [
  '@nuxtjs/sitemap'
],
sitemap: {
  hostname: 'https://YOUR_SITE.example'
}

ここまででサイトマップを生成することが可能になりますが、nuxt generateして生成されたdist/sitemap.xmlを見るとarticles以下の記述がありません。

dist/sitemap.xml
<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にルーティングの設定を追加します。
nuxt.config.js
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が追加されているのがわかります。

dist/sitemap.xml
<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のページを追加することができますので、ぜひお試しください。

参考サイト

@nuxtjs/sitemap - npm
発展的な機能 - Nuxt Content

共有する:

おすすめ記事

/profile_icon.png 管理人ボルト
情報系大学で勉強中。ゲームが大好き。独学でJavaを勉強し、趣味でBukkitプラグイン開発を行っています。今までに得た知識やノウハウ、最新情報などをお届けします。