外部にあるmarkdownファイルをAstroのContent collectionsに追加する
Astro 5.12.3 で、GitHub プロフィールをそのまま About ページに表示したくなった。 そこで他のリポジトリで公開している README.md を取得する loader を作成した。
次の記述で GitHub の README.md を Content collections に追加することが出来る。
typescript
// content.config.ts
const spec = defineCollection({
loader: {
name: "my-github-readmer",
load: async ({ renderMarkdown, store }) => {
const response = await fetch(
"https://raw.githubusercontent.com/hrdtbs/hrdtbs/refs/heads/master/README.md"
);
const entry = await response.text();
store.clear();
store.set({
id: "about",
data: {
entry,
},
rendered: await renderMarkdown(entry),
});
},
},
});
export const collections = {
// Other collections ...
spec,
};defineCollectionのloaderには、元々用意されているfileやglobを利用する方法Builit-in loadersだけでなく、自分でファイルを取得する関数を指定する方法Inline loadersや、今回利用したオブジェクトを指定する方法Object loadersがある。
恐らくInline loadersでも同様の記述が出来ると思うが、Object loadersの場合は引数からrenderMarkdownを取得することが出来るため、markdown ファイルを取得するようなケースでは手軽だと思われる。
Content collections に追加されるため、次のように利用できる。
ts
// src/pages/about.astro
---
import { getEntry, render } from "astro:content";
const aboutPost = await getEntry("spec", "about");
const { Content } = await render(aboutPost);
---
<Content />