アイキャッチ画像

AstroでSwiperを導入するには?npmを使った簡単ガイド

「スライダーをウェブサイトに追加したい!」そんな時に便利なのが、「Swiper」です。

本記事では、モダンな静的サイトジェネレーター「Astro」とSwiperを組み合わせ、簡単にスライダーを実装する方法を解説します。

npmを活用して効率よく導入する方法をご紹介します。

これでAstroでSwiperを使うのも怖くありません!

AstroへのSwiper導入手順

それでは実装方法の解説です。

ステップ1: npmでSwiperをインストール

まずはSwiperをインストールします。

以下のコマンドをターミナルで入力します。

npm i swiper

これでSwiperのインストールは完了です。

ステップ2: Swiperに関するコードを書く

次にSwiperに関するコードを書きます。

実際に私が使用しているSwiperのコンポーネントがこちらです。

Swiper.astro
---
import { Image } from "astro:assets";
import img from "../images/img.png";
---

<div class="swiper-container swiper-container1">
  <div class="swiper swiper1">
    <!-- swiper-wrapper 必須・名称変更不可 -->
    <div class="swiper-wrapper">
      <!-- swiper-slide 必須・名称変更不可 -->
      <div class="swiper-slide">
        <Image src={img} alt="" />
      </div>
      <div class="swiper-slide">
        <Image src={img} alt="" />
      </div>
      <div class="swiper-slide">
        <Image src={img} alt="" />
      </div>
    </div>
    <!-- If we need pagination -->
    <div class="swiper-pagination swiper-pagination1"></div>
  </div>
</div>

<style lang="scss">
  .swiper-container {
    max-width: 300px;
    height: auto;
  }
</style>

<script>
  import Swiper from "swiper";
  import "swiper/css/bundle";
  import { Autoplay, Pagination } from "swiper/modules";

  const swiper = new Swiper(".swiper1", {
    modules: [Autoplay, Pagination],
    loop: true,
    speed: 1000,

    autoplay: {
      delay: 4000,
      disableOnInteraction: false,
    },
    pagination: {
      el: ".swiper-pagination1",
      clickable: true,
    },
  });
</script>

実際に使用する時は通常のコンポーネントの呼び出しと同様です。

index.astro
---
import Swiper from "../components/Swiper.astro";
---
<Swiper />

ステップ3: スライダーのスタイルを調整する

スライダーのスタイル調整は<script>タグ内にて調整します。

まとめ

この記事ではこの記事ではAstroでnpmを使ってswiperをインストールして使う方法をご紹介しました。

npmを使うことで簡単にswiperを使うことができます。

是非皆さんも活用してみて下さい。

もしこの記事が役に立ったと感じていただけた方は、ぜひX(旧Twitter)やブログなどでシェアしていただけると嬉しいです。

最後までお読みいただき、ありがとうございました!

他にもこんな記事が読まれています

Webサイト制作に関する
ご相談はお気軽に。