サイトを Astro 5.0 にアップデートした

Astro 5.0

Astro 5.0が正式に登場した。アップデートしたので自分用のメモ。 Content Layer に関しては以前書いたので省略

Astro 5.0 | Astro
Astro 5.0 brings exciting new features like the Astro Content Layer for seamless content loading from any source, and Server Islands for effortlessly combining static and dynamic personalized content.
Astro 5.0 | Astro favicon https://astro.build/blog/astro-5/
Astro 5.0 | Astro

今まで画像の表示に利用していたastro-imagetoolsは最近sharp絡みのエラーも起きていて今回のAstro 5.0へのアップグレードを期に使用をやめAstro内蔵の画像コンポーネントを利用することにした。

Astro 5.0からは実験的機能としてレスポンシブイメージ機能が追加されている。

Images
Learn how to use images in Astro.
Images favicon https://docs.astro.build/en/reference/experimental-flags/responsive-images/#responsive-image-properties
Images

以下のように astro.config.mjs で設定する。

astro.config.mjs
import { defineConfig } from "astro/config";
export default defineConfig({
experimental: {
responsiveImages: true,
svg: true,
},
});

これでAstroのImageやPictureでcoverやpositionのプロパティが使えるようになる。

/src/assets/images にある画像を読み出すコンポーネント

/src/assets/images はTinaCMSが画像を保存するデフォルトのパス。現状ではブログカードの画像表示の切り出しに使っている。Imageコンポーネントで今まで指定できなかったfitやpositonを指定している

---
import type { ImageMetadata } from "astro";
import { Image } from "astro:assets";
interface Props {
className: string;
src: string;
width: number;
height: number;
alt: string;
}
const { className, src, width, height, alt } = Astro.props;
const images = import.meta.glob<{ default: ImageMetadata }>(
"/src/assets/images/**/*.{jpeg,jpg,png,gif,webp}"
);
if (!images[src]) {
throw new Error(
`"${src}" does not exist in glob: "/src/assets/images/**/*.{jpeg,jpg,png,gif,webp}"`
);
}
---
<Image
src={images[src]()}
class={className}
fit="cover"
position="north"
width={width}
height={height}
alt={alt}
loading="lazy"
/>

AstroのImageは画像を静的にインポートして使わなければいけないが動的にファイルを指定した場合が多々あある。そのようなときのために公式でも動的な画像のインポート指定方法が解説されている。

Dynamically import images
Learn how to dynamically import images using Vite's import.meta.glob function.
Dynamically import images favicon https://docs.astro.build/en/recipes/dynamically-importing-images/
Dynamically import images

上記を参考に/src/assets/images/ から始まる画像のパスを指定してコンポーネントを呼び出すとそのパスからimageオブジェクトを生成してAstroのImageに渡し表示する。

Markdownファイルのfeaturedは /src/assets/images/ から始まるので上記のコンポーネントで表示する。

---
featured: /src/assets/images/note/logo/astro-cool-parts.png

Markdown本文内で読み込む画像は相対パスで表記せねばならず /src/assets/ から始まる絶対パスではエラーを起こすし外部URL画像も読む上にmdxではないmdファイルの場合もあるので以前のままの処理とした。

![plugins](../../assets/images/note/obsidian/plugins.webp)

このように相対パス指定にしないとエラーが起こり画像が表示されなくなる。

Bridgy Fed の u-photo クラス問題

Bridgy Fedのための u-photo クラス自動付与がastro-remark-eleventy-image を使わなくなったことでできなくなり以下のようなコンポーネントが必要になった。

参考にしたサイト

gensobunya-tech.hatenablog.com
gensobunya-tech.hatenablog.com favicon https://gensobunya-tech.hatenablog.com/entry/2023/10/21/141555

通常のmdファイルでは画像変換が行われないのでMarkdownに貼られた画像をBridgy Fedに送りたい時はmdxファイルにする必要がある。