4
votes

I want to add swiper slider to svelte, my question is:

  1. Its possible to add css in script tag, like this:
<script> import from "styles.css" ... </script> 

Because import to head is tricky (Import css in node_modules to svelte)

  1. I add swiper.js file to svelte, and it almost works. It works on touch (mouse), but buttons don't (.swiper-button-next .swiper-button-prev). Do exist special import .js files rules ?

Code example: https://codesandbox.io/s/musing-leavitt-ygstx?file=/App.svelte:224-243

1

1 Answers

4
votes
  1. With rollup you can just import the css file like you will do for a .js module:
<script>
  import { onMount } from "svelte";
  import "swiper/swiper-bundle.min.css"; // <- just import your css
  ...
</script>
  1. For the navigation issue it's written in the swiper documentation:

By default Swiper exports only core version without additional modules (like Navigation, Pagination, etc.). So you need to import and configure them too:

// core version + navigation, pagination modules:
import Swiper, { Navigation, Pagination } from 'swiper';

// configure Swiper to use modules
Swiper.use([Navigation, Pagination]);

// init Swiper:
const swiper = new Swiper(...);

So finally, your component initialisation can be done like that:

<script>
  import { onMount } from "svelte";
  import "swiper/swiper-bundle.min.css";
  import Swiper, { Navigation } from "swiper";

  Swiper.use([Navigation]);

  onMount(() => {
    const swiper = new Swiper(".swiper-container", {
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev"
      }
    });
  });
</script>

Here's the link for the codesandbox.