Astro.js `.astro` ファイルでクライアント側で npm モジュールを使用する方法


私はAstroでもう少し遊んでいて、最終的に.astroファイルでnpmモジュールのクライアント側を使用する方法に頭を悩ませました.それはそれほど明白ではありません...

最初に試したのは次のようなものでした:

<!-- Test.astro -->
<canvas class="webgl"></canvas>

<script type="module"> 
 import * as THREE from 'three'

 console.log(THREE) //undefined :(
</script>


これにより、コンソールに Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../". が返されます.

Astro では、.astro 残念ながら、インライン スクリプト タグで npm モジュールをインポートできません.ただし、外部の .js/.ts ファイルをインポートして、次のように Astro.resolve を使用できます.

<!-- Test.astro -->
<canvas class="webgl"></canvas>

<script src={Astro.resolve('./myScript.js')} type="module"/>

myScript.js の内部では、期待どおりにインポートできます.

// myScript.js
import * as THREE from 'three';

console.log(THREE) // Three.js module!


作業デモ here .