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

    AstroでKaTeXで書いた数式をMathMLに変換して表示する

    当ブログはAstroというSSG(静的サイトジェネレータ)を使っている。また、記事はMarkdownを拡張したMDXというフォーマットを用いて書いている。

    数学で学んだことを記事にする際、プレーンテキストでは微積分や行列などの数式を表現することが難しい。そのため、KaTeX(LaTeXのJavaScriptライブラリ)の記法を使ってコードブロック内に数式を表現したい。

    ```math
    \int_{a}^{b} f(x) dx
    ```

    ライブラリ選定基準

    rehype-katex

    rehype-katexを使うことにした。READMEにはunified()を使ったり、JavaScript やCSSを読み込んだりという記述があるが、Astroで使う場合には不要だった。

    rehype-katexをインストールし、astro.config.mjsに設定を追加するだけで、mathのコードブロックをMathMLに変換してくれる。

    $ npm install -S rehype-katex
    // astro.config.mjs
    import { defineConfig } from 'astro/config';
    import mdx from '@astrojs/mdx';
    import rehypeKatex from 'rehype-katex'
    
    // https://astro.build/config
    export default defineConfig({
      integrations: [
        mdx(),
      ],
      markdown: {
        rehypePlugins: [rehypeKatex]
      }
    });

    設定

    rehype-katexはデフォルトで、HTMLとMathMLの両方を出力する設定になっているため、outputオプションでMathMLのみに限定する。

    また、mathブロック内で日本語などを使うと警告が出力されるので、あまり良くはないがstrictモードを無効にした。

    export default defineConfig({
      integrations: [
        mdx(),
      ],
      markdown: {
        rehypePlugins: [
          [
            rehypeKatex,
            {
              strict: false,
              output: 'mathml'
            }
          ]
        ]
      }
    });

    上記の場合は、Optionsの型が効かないので、以下のような書き方も良さそうだ。

    export default defineConfig({
      integrations: [
        mdx(),
      ],
      markdown: {
        rehypePlugins: [
          (...args) => rehypeKatex({
            ...args,
            strict: false,
            output: 'mathml'
          })
        ]
      }
    });