-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
publish 2024-08-05-using-dynamic-import-for-astro-assets
- Loading branch information
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
51 changes: 51 additions & 0 deletions
51
src/content/blog/2024-08-05-using-dynamic-import-for-astro-assets.mdx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
--- | ||
title: 'Astroのアセットをdynamic importで読み込んで間接的な変数をなくす' | ||
pubDate: 2024-08-05T04:08:20.000+09:00 | ||
--- | ||
|
||
Astroにおいて、コンポーネントから画像などのアセットを読み込む場合、import文を使うことが一般的だ。 | ||
|
||
```astro | ||
--- | ||
import { Image } from 'astro:assets'; | ||
import logoImage from '../assets/logo.svg'; | ||
--- | ||
<Image src={logoImage} alt="Yuhei Yasuda" /> | ||
``` | ||
|
||
しかし、このような書き方をするとやや不便なことがある。それはimport文を使うと、実際にアセットを使用する箇所から離れた部分に記述が分散するため、一見して対応関係がわかりづらくなることである。例のように行数の少ないファイルではそれほどではないが、行数の多いファイルでは、離れた箇所に記述すると非常に煩わしいことになる。 | ||
|
||
そこで、代わりにdynamic importを使うことで、アセットの読み込みをインライン化することができる。`<Image />`コンポーネントの`src` propはPromiseに対応しているため、ここで直接dynamic importを使用できる。 | ||
|
||
```astro | ||
--- | ||
import { Image } from 'astro:assets'; | ||
--- | ||
<Image src={import('../assets/logo.svg')} alt="Yuhei Yasuda" /> | ||
``` | ||
|
||
普通JavaScriptのアプリケーションでは、code splittingを有効にするためにdynamic importを使うが、この場合ではビルドへの影響はない。 | ||
|
||
ただし、Promiseを解決するためにawaitが必要な場合は都合が悪い。Astroコンポーネントにおいては、コードフェンスの外側ではawaitを使用できず、awaitを使うためにはコードフェンスの内側に記述しなければならないからだ。したがって、直接パスを参照したければ、けっきょくは変数化せざるを得ない。 | ||
|
||
```astro | ||
--- | ||
import { Image } from 'astro:assets'; | ||
const logoImage = (await import('../assets/logo.svg')).default; | ||
--- | ||
<img src={logoImage.src} alt="Yuhei Yasuda" /> | ||
``` | ||
|
||
このような場合では、あえてdynamic importを使う理由はない。 | ||
|
||
一方、Astroコンポーネントではなく、MDXファイルの中ではawaitを使うことができる。そのため、dynamic importを活用した記述が可能である。 | ||
|
||
```mdx | ||
<video controls> | ||
<source src={(await import('./assets/video.webm')).default} type="video/webm" /> | ||
</video> | ||
``` |