Site cover image
Astro フックを使って任意のタイミングで処理を差し込む

Astroには前処理など任意のタイミングで何らかの処理を実行したいとき、フックを使って処理を差し込むことができます。

この記事ではAstroでフックを使う方法を説明します。

Hooks

フックは、Astro側であらかじめ定義されたタイミングで開発者が任意の処理を差し込める仕組みです。

フックにはビルド開始直前を表す astro:build:start やconfigの設定完了直後を表す astro:config:done などがあります。

詳細は下記の公式ドキュメントをご覧ください。

例えば astro:build:start フックを使って何らかの処理を実装したとき、インテグレーションを定義して処理を記述します。

インテグレーション

インテグレーションを定義するために src/integrations ディレクトリを作成します。

ここでは記事ごとのOG画像を事前にアップロードする og-image-uploader インテグレーションを例に説明します。

src/integrations/og-image-uploader.ts を下記のように作成しました。

import type { AstroIntegration } from 'astro'
import { getAllPosts } from '../lib/notion/client'
import { uploadImageWithKey } from '../lib/cloudinary/client'

export default (): AstroIntegration => ({
  name: 'og-image-uploader',
  hooks: {
    'astro:build:start': async () => {
      const posts = await getAllPosts()

      await Promise.all(posts.map(post => {
        if (post.FeaturedImage) {
          return uploadImageWithKey(post.FeaturedImage, post.PageId)
        }
        return Promise.resolve()
      }))
    },
  },
})
インテグレーションを定義する

インテグレーションは AstroIntegration インターフェイスを満たしている必要があります。

AstroIntegration インターフェイスは下記ページに説明があります。

name には任意の名前を設定し、hooks に任意にフックを定義します。

今回はビルド直前を表す astro:build:start を定義しています。

戻り値は void | Promise<void> である点に注意しましょう。必要な処理は return なしに実行します。

上記の例では Promise.all() で並列に処理を実行しています。

定義したインテグレーションは astro.config.mjs で設定します。

下記は公式ドキュメントです。

下記のようにして defineConfigintegrations に渡してあげることで設定できます。

// ...
import OGImageUploader from './src/integrations/og-image-uploader'

// ...
export default defineConfig({
  site: '...',
  integrations: [
    OGImageUploader(),
  ],
})
astro.config.mjs で定義したインテグレーションを読み込む

正しく設定できていれば、ビルド実行時に下記のようなログが見つかるはずです。

Waiting for the og-image-uploader integration...
正常に実行されるとビルド時のログに現れる

以上です。この記事ではAstroでフックを使う方法を説明しました。

Thank you!
Thank you!
URLをコピーしました

コメントを送る

コメントはブログオーナーのみ閲覧できます