≪ Today I learned. RSS購読
公開日
タグ
JavaScript
著者
ダーシノ(@bc_rikko)

AstroでMermaid記法を使う

当ブログはAstro + mdxで構成されている。

図解するとき、いままではプレーンテキストでAAのような書き方をしていたが、書くのが大変なのでMermaid記法を使いたい。

+--------+       +-------+
| User   |       | Admin |
+--------+ <|--- +-------+
| +name  |       |       |
| +email |       +-------+
+--------+

AstroでMermaidを使う

AstroでMermaid記法を変換するためには、rehype-mermaidを使う。

npm i rehype-mermaid
// astro.config.js
import rehypeMermaid from 'rehype-mermaid'
import { defineConfig } from 'astro/config'

export default defineConfig({
  ...,
  markdown: {
    syntaxHighlight: {
      type: 'shiki',
      excludeLangs: ['mermaid'],
    },
    rehypePlugins: [
      rehypeMermaid,
    ]
  }
})

GitHub Actionsでビルドできようにする

rehype-mermaidはPlaywrightを使っているため、CI環境でヘッドレスブラウザのインストールが必要になる。

# playwright本体をインストールする
# ※ヘッドレスブラウザはビルドのステップでインストールする
npm i -D playwright

当ブログのBuild&DeployはGitHub Actionsのwithastro/actionを使っており、npx playwright install --with-deps chromiumみたいなステップを追加することができない。

かといってnodeのセットアップなどを自分でやりたくないので、npm scriptsのprebuildを使ってブラウザをインストールする方法を採用した。

{
  "scripts": {
    "prebuild": "npx playwright install --with-deps chromium",
    "build": "astro build"
  }
}

ブラウザの容量が大きいため、ビルド時間が1分ほど長くなってしまった…。

Mermaid記法を試す

```mermaid
---
title: https://mermaid.js.org/syntax/classDiagram.html
---
classDiagram
    note "From Duck till Zebra"
    Animal <|-- Duck
    note for Duck "can fly\ncan swim\ncan dive\ncan help in debugging"
    Animal <|-- Fish
    Animal <|-- Zebra
    Animal : +int age
    Animal : +String gender
    Animal: +isMammal()
    Animal: +mate()
    class Duck{
        +String beakColor
        +swim()
        +quack()
    }
    class Fish{
        -int sizeInFeet
        -canEat()
    }
    class Zebra{
        +bool is_wild
        +run()
    }

```

Animal

+int age

+String gender

+isMammal()

+mate()

Duck

+String beakColor

+swim()

+quack()

Fish

-int sizeInFeet

-canEat()

Zebra

+bool is_wild

+run()

From Duck till Zebra

can fly\ncan swim\ncan dive\ncan help in debugging

https://mermaid.js.org/syntax/classDiagram.html