DEV Community

Alex Chiu
Alex Chiu

Posted on • Edited on • Originally published at learning.chiubaca.com

How to use npm modules client-side in Astro.js `.astro` files

I've been playing with Astro some more and finally got my head around how to use npm modules client side in a .astro file. It's not that obvious...

First thing I tried was something like this:

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

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

 console.log(THREE) //undefined :(
</script>
Enter fullscreen mode Exit fullscreen mode

This returns Uncaught TypeError: Failed to resolve module specifier "three". Relative references must start with either "/", "./", or "../". in the console.

Astro doesnt let you import npm modules in inline script tags within .astro unfortunatley. However we can import in an external .js/.ts file, then make use of Astro.resolve like so:

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

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

Inside myScript.js we can import things as expected.

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

console.log(THREE) // Three.js module!
Enter fullscreen mode Exit fullscreen mode

Working demo here.

Top comments (2)

Collapse
 
gergelyszabo94 profile image
Gergely Szabo • Edited

I was trying to achieve the same but with lightbox but got this deprecation warning from astro that helped me solved a nicer way.

I deleted my "importLightbox.js" file and did it like this:
<script>
import "lightbox2/dist/js/lightbox.min.js"
</script>

Collapse
 
amiceli profile image
amiceli

Just thanks, you save my day !