What steps do I need to follow in order to incorporate and utilize an npm package within my Astro component

I have been working on integrating KeenSlider into my project by installing it from npm. However, I am encountering an error message that says

Uncaught ReferenceError: KeenSlider is not defined
whenever I try to use the package in my Astro component.

Below is a snippet of 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 attempted using

import KeenSlider from "keen-slider"
, and
import { useKeenSlider } from "keen-slider"
(with and without brackets), but these did not resolve the issue.

I have not made any modifications to my astro.config.mjs file, as I believe installation via npm and referencing in the component should cover everything with Astro's handling. However, there seems to be a mistake on my end. How can I properly define 'KeenSlider'?

Answer №1

To incorporate client-side scripts into your project, simply utilize standard HTML <script> tags. Astro will manage and package these tags, enabling functionality such as importing npm modules, TypeScript integration, and more.

As demonstrated in the example, ensure that the keen-slider import is placed within the <script> tag.

<script>
import KeenSlider from "keen-slider";

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

For a practical illustration, refer to this link, where I also include the import of keen-slider CSS.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Analyze the JSON data retrieved from the API endpoint to determine any

I am currently attempting to utilize axios to send an API request in order to validate login credentials, but I am facing difficulties retrieving the result from the API. The MongoDB .find function successfully locates the correct row, however, I am encoun ...

Showcasing a graphical representation with the help of Highcharts

I am currently exploring JavaScript and trying to familiarize myself with interactive charts using the HighCharts library. Unfortunately, I have been facing some challenges in getting the graph to print correctly. Despite attempting various examples, none ...

I encountered an error while trying to synchronize my Redux state with the component state

Upon clicking the advanced sports search button, I need to display a drawer containing my API values. Currently, when mapping my Redux state with component state, an error is occurring stating "Actions must be plain objects. Use custom middleware for async ...

Unable to install serialport with npm (or 'node-gyp rebuild') when not connected to the internet

Attempting to install the serialport package (a dependency of oxygen-cli) within our internal network without internet access is proving to be a challenge. During the npm install -g serialport process, it attempts to rebuild node-gyp. After encountering a ...

Excessive API requests can occur when Redux dispatches an action multiple times

Utilizing the Jikan API for anime, my objective is to showcase promo thumbnails of new anime shows. This involves two separate API calls: one to retrieve the latest anime shows: export const get_new_anime = () => `${base_url}search/anime?q&order_b ...

Reacting - page is not refreshing

Describing my current scenario: I have a requirement where I need to be able to navigate to a /details page by clicking on an image. However, when I click on the image, the URL gets refreshed but my component does not load. I attempted various solutions ...

Having trouble adding a test card to the Google Pay testing environment and calculating the order total

How can I display the order total in GooglePay payment sheet? I could not find any documentation on this. Is it possible to do so? Even though I am using the TEST environment, I am unable to add any test card as mentioned in the URL provided below. Additio ...

jQuery ajaxSetup: handling error retries for ajax calls is not possible

When using $.ajaxSetup(), I am faced with the challenge of making an AJAX request after refreshing a valid token in case the previous token has expired. The issue arises when attempting to execute $.ajax(this) within the error callback. $.ajax({ url: ...

Retrieve the current time of day based on the user's timezone

Currently, I am working with a firebase cloud function that is responsible for sending push notifications to my app. My main requirement is to send notifications only during the day time. To achieve this, I have integrated moment-timezone library into my p ...

Show the image on top of the div block as the AJAX content loads

Implementing this task may seem easy and common, but I am struggling to figure it out! What should take five minutes has turned into an hour of frustration. Please lend me your expertise in getting this done. I have a div container block: <div cla ...

Unable to load CSS background image

As I develop a website for a fictional company to enhance my skills in HTML, CSS, and JavaScript, I am encountering an issue with loading my background image. If someone could review my code to identify the problem, I would greatly appreciate it. Check ou ...

Using knockout to data bind a function to an onclick event that takes in multiple parameters

I've scoured the internet and experimented with various methods, but I'm encountering an issue where the click function intermittently fails to fire. Below is my HTML code snippet: <input type="radio" data-bind="checked:a, checkedValue: 0 ...

What is the best way to make a Firestore request that relies on the initial Firebase response in Next.js?

Is there a way to perform a second cloud Firestore query using the uid obtained in the first query, without the second query executing before receiving the response from the first one? Here's my code: var {data} = useSWR('/api/report', fet ...

Guide on sending a push notification using "npm request" to the Ionic API

I attempted to send a push notification through the Ionic API using "npm request". Here is my code: var request = require('request'); var token = '................'; var title = escapeJson('title 123'); var message = escapeJ ...

How Can You Update the State of a Parent Component from a Child Component?

My Objective In the initial component, I retrieve items with a status of 2 and display them as checkboxes. In the subsequent component, I update the status of these items to 3. In the third component, a modal opens after the status change from the secon ...

What is the best way to combine a string with a variable in sass?

Is there a way to merge a string and a variable in Sass to form a variable name that is already present? $size: "sm"; $button-sm: 1rem; $buttom-md: 1.5rem; body { font-size: $button-#{$size}; } The desired output is: body { font-size: 1r ...

What is the best way to combine relative paths or create distinct identifiers for SVG files located within multiple layers of folders

I have a collection of icons exported from "Figma" organized in folders, and I'm using grunt-svgstore to create a sprite sheet. However, the result contains duplicated IDs even after trying 'allowDuplicateItems: false' and 'setUniqueIds ...

Tracking global click events in Vue.js can provide valuable insights into user interactions on your

While working with JavaScript, I was able to create this code for a popover. By clicking on the navbar-link element, the popover will appear or disappear. However, it would be great if I could close the popover by clicking anywhere on the screen (when the ...

Is there an easy method for sorting through JSON data with various criteria?

After receiving a response from my web service containing an array of objects, I am looking to filter the data based on various combinations of values. What is the most efficient way to do this without impacting the performance of my web service? Data: Th ...

When I try to run npm run build in a Vagrant environment on Windows 10, I receive an error message saying "rimraf: not found"

I am attempting to run a webpack project in Vagrant (on Windows 10) with an embedded Ubuntu 16.04 virtual machine. Successfully installed npm 5.6.0 and nodejs v8.9.4. After running npm install for dependencies, encountered the following errors : ... gyp ...