Open3

Astro + MDX + Cloudflare Pages メモ

voluntasvoluntas

モチベーション

ロードマップサイトを作ろうと思ったが Sphinx ではでかすぎるので markdown をレンダリングしたサイトを作ろうと思った。

Astro と MDX の組み合わせがシンプルでよさそうで、かつ Cloudflare Pages へのデプロイも簡単なので採用してみることにした。

voluntasvoluntas

Astro

静的サイトを気軽に作るフレームワーク。React やら Svelte やらなんでも使える。

Astro | Build faster websites

デプロイ先も豊富。

Astro MDX

npx astro add mdx でサクッと使える。src/pages/index.mdx と src/layouts/IndexLayout.astro を用意しただけ。

Astro Cloudflare

npx astro add cloudflare したら後は Cloudflare Pages の設定をするだけ。npm run build して勝手にデプロイしてくれる。

voluntasvoluntas

ヘッダーリンクを付けたい

mdx レンダリング時に自動で slug 化したヘッダーリンクを付けたい。さくっとは行かなそうで色々頑張る必要がある模様。

実際に組み込んだのは以下のコードを参考にした。
Astro Blog Example (forked) - StackBlitz

import { defineConfig } from 'astro/config';
import mdx from "@astrojs/mdx";
import rehypeSlug from 'rehype-slug';
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
import { s } from 'hastscript';

// https://astro.build/config
import cloudflare from "@astrojs/cloudflare";
export default defineConfig({
  integrations: [mdx({
    rehypePlugins: [
      rehypeSlug,
      [rehypeAutolinkHeadings,
        {
          behavior: 'prepend',
          // SVG でヘッダーリンクを作る
          content: (node) => [
            s(
              'svg',
              {
                class: 'slug-svg',
                viewBox: '0 0 16 16',
                version: '1.1',
                width: '1.0rem',
                height: '1.0rem',
              },
              [
                s('path', {
                  fillRule: 'evenodd',
                  d: 'M7.775 3.275a.75.75 0 001.06 1.06l1.25-1.25a2 2 0 112.83 2.83l-2.5 2.5a2 2 0 01-2.83 0 .75.75 0 00-1.06 1.06 3.5 3.5 0 004.95 0l2.5-2.5a3.5 3.5 0 00-4.95-4.95l-1.25 1.25zm-4.69 9.64a2 2 0 010-2.83l2.5-2.5a2 2 0 012.83 0 .75.75 0 001.06-1.06 3.5 3.5 0 00-4.95 0l-2.5 2.5a3.5 3.5 0 004.95 4.95l1.25-1.25a.75.75 0 00-1.06-1.06l-1.25 1.25a2 2 0 01-2.83 0z',
                }),
              ]
            ),
          ],
        },
      ],
    ],
    extendPlugins: 'astroDefaults',
  })],
  output: "server",
  adapter: cloudflare()
});

上の設定をすると、こんな感じでリンクが作れる
https://roadmap.shiguredo.jp/

もっと言いやり方があるといいのだが ... 。