フロントエンド

Astroにシンタックスハイライト済みのHTMLを配信する方法!

Astroにシンタックスハイライト済みのHTMLを配信する方法!

こんにちは、Astroでシンタックスハイライト済みのHTMLを配信する方法についてご紹介します。

Astroは、Next.jsやSvelteのような静的サイトジェネレーターで、高速でシンプルな開発が可能です。

それでは、Astroでシンタックスハイライト済みのHTMLを配信する方法を見ていきましょう。

1. Astroプロジェクトを作成する


まずは、Astroプロジェクトを作成します。以下のコマンドを実行して、Astroのテンプレートをダウンロードします。

npx create-astro-app my-app


2. highlight.jsをインストールする


まずは、highlight.jsをインストールします。以下のコマンドを実行します。

npm install -D  highlight.js


3.cheerioをインストールする

以下のコマンドを実行します。

npm install -D  cheerio


4. Astroでシンタックスハイライトを行う


最後に、Astroでシンタックスハイライトを行います。以下のように、highlight.js
の機能を利用して、コードブロックをシンタックスハイライトします

---
import Layout from "../layouts/Layout.astro";
import { getBlogs, getBlogDetail } from "../library/microcms";
import cheerio from "cheerio";
import hljs from "highlight.js";
import "highlight.js/styles/night-owl.css";


//記事の詳細情報を取得
const { blogId } = Astro.params;
const blog = await getBlogDetail(blogId as string);


const $ = cheerio.load(blog.content); // data.bodyはmicroCMSから返されるリッチエディタ部分
$("pre code").each((_, elm) => {
  const result = hljs.highlightAuto($(elm).text());
  $(elm).html(result.value);
  $(elm).addClass("hljs");
});
console.log($.html()); // ハイライト済みのHTML


// 詳細記事ページの全パスを取得
export async function getStaticPaths() {
  const response = await getBlogs({ fields: ["id"] });
  return response.contents.map((content: any) => ({
    params: {
      blogId: content.id,
    },
  }));
}
---


<Layout title="My first blog with Astro">
  <main>
    <h1 class="title">{blog.title}</h1>
    <p class="publishedAt">公開日時:{blog.publishedAt}</p>
    <div class="post" set:html={$.html()}></div>
  </main>
</Layout>