4

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

johannchopin
  • 13,720
  • 10
  • 55
  • 101

1 Answers1

4
  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.

johannchopin
  • 13,720
  • 10
  • 55
  • 101
  • Thanks for the answer, i insert your example to project (routify template - https://routify.dev/guide/installation) and get the error: [!] Error: Unexpected character '@' (Note that you need plugins to import files that are not JavaScript). It disappear when i remove - import "swiper/swiper-bundle.min.css"; – vladbelozertsev Aug 28 '20 at 18:12
  • it wokrs with sapper, looks like need to add some loader to rollup – vladbelozertsev Aug 28 '20 at 18:53
  • Yes you will need a plugin like [rollup-plugin-css-only ](https://www.npmjs.com/package/rollup-plugin-css-only) for example. So does it respond your question? – johannchopin Aug 28 '20 at 19:55
  • Yes, you helped me a lot. Thanks, and pls add to answer the plugin, mb its help somebody :) – vladbelozertsev Aug 28 '20 at 20:06
  • @vladbelozertsev Could you also please don't forget to upvote my answer ? :) – johannchopin Sep 22 '20 at 20:06