#How can I use Swiper.js in my astro project ? I am not using any framework, but simple vanillajs

1 messages · Page 1 of 1 (latest)

wet bobcat
#

I get this error :

document is not defined
Hint:
Browser APIs are not available on the server.

If the code is in a framework component, try to access these objects after rendering using lifecycle methods or use a `client:only` directive to make the component exclusively run on the client.

See https://docs.astro.build/en/guides/troubleshooting/#document-or-window-is-not-defined for more information.

File:
C:\Users..\website\node_modules\swiper\shared\swiper-core.mjs:3681:7
Code:
3680 | if (typeof el === 'string') {

3681 | el = document.querySelector(el);
| ^
3682 | }
3683 | if (!el) {
3684 | return false;
Stacktrace:
ReferenceError: document is not defined
at Swiper.mount (file:///C:/Users/../website/node_modules/swiper/shared/swiper-core.mjs:3681:7)
at Swiper.init (file:///C:/Users/../website/node_modules/swiper/shared/swiper-core.mjs:3726:28)
at new Swiper (file:///C:/Users/../website/node_modules/swiper/shared/swiper-core.mjs:3427:14)

Astro Documentation

Need help? Stuck on something? We've got you covered.

surreal fog
#

Hello @wet bobcat, it is hard to tell. Do you happen to have this in a repo?

#

Or can you share a snippet where you're trying to use this package?

wet bobcat
#

Hello, no I don't have it in a repo. However I can share a snippet of the code. @surreal fog

`---
// import Swiper JS
import Swiper from 'swiper';
// import Swiper styles
import 'swiper/css';

const swiper = new Swiper('.swiper', {

effect:'fade',

});


<section class="container mx-auto px-64 py-16">

<!-- Slider main container -->

<div class="swiper w-[700px] h-[600px]">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide bg-black p-20 rounded-[48px]">Slide 1</div>
<div class="swiper-slide bg-yellow-900 p-20 rounded-[48px] ">Slide 2</div>
<div class="swiper-slide bg-orange-600 p-20 rounded-[48px] ">Slide 3</div>
...
</div>
</div>

</section>`

Here it is.

I have installed it using npm install swiper

surreal fog
#
<script>
swiper code
</script>
wet bobcat
#

Thanks it works now

surreal fog
#

cool, glad it solved your issue