'Install swiper slider on Laravel project

how can I install the swiper slider package on my Laravel 9 project?

Package link : swiperjs.com



Solution 1:[1]

The correct version of integration into Laravel 8/9 using webpack that does not contradict the swiper documentation may look like this:

Install swiperjs :

npm install swiper

Then inside the file resources/sass/app.scss :

@import 'node_modules/swiper/swiper';

if you need navigation/pagination or another modules add lines:

@import 'node_modules/swiper/modules/navigation/navigation';
@import 'node_modules/swiper/modules/pagination/pagination';

And inside the file /resources/js/app.js :

import { Autoplay, Navigation, Pagination } from "swiper";
import Swiper from "swiper";
Swiper.use([Autoplay, Navigation, Pagination]);

(in the example above, I added Autoplay property). And after then where to add the code (for example in blades):

<div class="swiper mySwiperClass">
    <div class="swiper-wrapper">
        <!-- Slides -->
        <div class="swiper-slide">Slide 1</div>
        <div class="swiper-slide">Slide 2</div>
        <div class="swiper-slide">Slide 3</div>
        ...
    </div>
    <!-- If we need pagination -->
    <div class="swiper-pagination"></div>
    <!-- If we need controls 
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
    -->
</div>

<script>
    window.onload = function(){
        const swiper = new Swiper('.mySwiperClass', {
            spaceBetween: 15,
            slidesPerView: 3, 
            pagination: {
              el: ".swiper-pagination",
              clickable: true
            },
            speed: 1000,
            loop: true,
            autoplay: {
              delay: 2500,
              disableOnInteraction: false,
            }
        }
    }
</script>

Solution 2:[2]

Well I guess this is the only answer on the internet that properly installs swiperjs in laravel (v9.x) and works.

Caution : According to the comment and provided link by @ktscript, the following approach is a bad practice which is recommended not to use by swiper official website.

But still I won't delete my answer in case you don't have any other options on the table.

If you've found it useless just let me know in the comments so I'll delete my answer.

Install swiperjs :

npm install swiper

Then inside the file resources/sass/app.scss :

@import 'node_modules/swiper/swiper';

Notice: You can't import the styles with a ~ at the beginning.

And inside the file /resources/js/app.js :

const Swiper = require('swiper').default;

The .default is necessary after require().

UPDATE : Now I found out that I can import swiper like below.

import {Swiper, Navigation, Pagination} from 'swiper';

Tested with Laravel v9.x and swiperjs v8.x.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ktscript
Solution 2