302 文字
2 分

外部にあるmarkdownファイルをAstroのContent collectionsに追加する

2025-07-26

Astro 5.12.3 で、GitHub プロフィールをそのまま About ページに表示したくなった。 そこで他のリポジトリで公開している README.md を取得する loader を作成した。

次の記述で GitHub の README.md を Content collections に追加することが出来る。

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,
};

defineCollectionloaderには、元々用意されているfileglobを利用する方法Builit-in loadersだけでなく、自分でファイルを取得する関数を指定する方法Inline loadersや、今回利用したオブジェクトを指定する方法Object loadersがある。

恐らくInline loadersでも同様の記述が出来ると思うが、Object loadersの場合は引数からrenderMarkdownを取得することが出来るため、markdown ファイルを取得するようなケースでは手軽だと思われる。

Content collections に追加されるため、次のように利用できる。

src/pages/about.astro
---
import { getEntry, render } from "astro:content";
const aboutPost = await getEntry("spec", "about");
const { Content } = await render(aboutPost);
---
<Content />
外部にあるmarkdownファイルをAstroのContent collectionsに追加する
https://blog.ohirunewani.com/posts/astro-external-markdown-loading/
作者
hrdtbs
公開日
2025-07-26
ライセンス
CC BY-NC-SA 4.0