[Astro] @astrojs/rss と @astrojs/sitemap でRSS・サイトマップを出力する
TechWordPress では RSS もサイトマップもプラグイン任せでしたが、Astro では公式パッケージで両方さくっと用意できます。移行のついでに入れたのでメモ。
インストール
npm i @astrojs/rss @astrojs/sitemap
サイトマップ(@astrojs/sitemap)
サイトマップはインテグレーションとして登録するだけ。ビルド時に sitemap-index.xml などが自動生成されます。
// astro.config.mjs
import { defineConfig } from 'astro/config';
import sitemap from '@astrojs/sitemap';
export default defineConfig({
site: 'https://nao-guitarist.com', // ★ site は必須
integrations: [sitemap()],
});
注意点は site を必ず設定すること。サイトマップは絶対URLを書き出すので、site が無いと生成されません。
RSS(@astrojs/rss)
RSS はエンドポイントとして作ります。src/pages/rss.xml.ts を置くと、/rss.xml で配信されます。
// src/pages/rss.xml.ts
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
import type { APIContext } from 'astro';
export async function GET(context: APIContext) {
const posts = (await getCollection('blog'))
.filter((p) => !p.data.draft)
.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf());
return rss({
title: 'nao-guitarist.com',
description: 'Naoki Asayama の個人ブログ',
site: context.site!,
items: posts.map((post) => ({
title: post.data.title,
description: post.data.description || '',
pubDate: post.data.pubDate,
link: `/blog/${post.id}/`,
categories: [post.data.category],
})),
});
}
ポイント。
- ファイル名は
rss.xml.ts。.xml.tsにしておくと出力パスが/rss.xmlになる。 siteはcontext.siteから取れる(astro.configのsiteの値)。itemsは Content Collections の記事から組み立てる。draft除外と日付降順は一覧と同じ処理。
RSS の場所をブラウザ・リーダーに知らせる
<head> に alternate link を入れておくと、RSS リーダーやブラウザが自動で見つけてくれます。
<link
rel="alternate"
type="application/rss+xml"
title="nao-guitarist.com"
href="/rss.xml"
/>
確認
ビルドして、それぞれ生成されているか見ます。
npm run build
ls dist/rss.xml dist/sitemap-index.xml
両方できていれば OK。RSS は /rss.xml、サイトマップは /sitemap-index.xml(+ sitemap-0.xml)で配信されます。サイトマップは Google Search Console に登録しておくと、移行後のクロールがスムーズでした。
Astro, SEO