サイトを 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 からは 実験的機能として レスポンシブイメージ機能が追加されている。

Experimental responsive images
Experimental responsive images favicon https://docs.astro.build/en/reference/experimental-flags/responsive-images/#responsive-image-properties
Experimental responsive 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 ファイルにする必要がある。