Search code examples
javascriptnpmastrojs

How can I import and use npm package in my Astro component?


I have installed KeenSlider from npm into my project, but I keep encountering a Uncaught ReferenceError: KeenSlider is not defined when attempting to use the package in my Astro component.

Here's my astro file:

---
import KeenSlider from "keen-slider";
---
<div id="carousel" class="keen-slider">
  <div class="keen-slider__slide">
     <h4>1</h4>
  </div>
  <div class="keen-slider__slide">
     <h4>2</h4>
  </div>
</div>
<script lang="js">
   var slider = new KeenSlider("#carousel", {
      slidesPerView: 1.25,
      spacing: 30,
   });
</script>

I have also tried import KeenSlider from "keen-slider", and import { useKeenSlider } from "keen-slider" (with and without brackets) as well with no luck.

I haven't made any changes to my astro.config.mjs file, as my understanding is that I don't need to - all I should have to do is install via npm, and reference it in the component I'm using it, and Astro handles the rest.

But clearly I'm doing something wrong. So how can I properly define 'KeenSlider'?


Solution

  • Client-side scripts can be added using standard HTML <script> tags. Astro will processes and bundles these tags, adding support for importing npm modules, writing TypeScript, and more.

    This means that in your example, the keen-slider import should be moved to the <script> tag.

    <script>
    import KeenSlider from "keen-slider";
    
    const slider = new KeenSlider("#carousel", {
        slidesPerView: 1.25,
        spacing: 30,
    });
    </script>
    

    You can also find a working example here where I import keen-slider CSS too.