1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swiperを使おうと思ったら「〇〇が動かない!」となった場合

Last updated at Posted at 2025-06-16

高機能なスライダー・カルーセルを簡単に実装できるJSライブラリ「Swiper」

Swiperは高機能なスライダー/カルーセルを簡単に導入できるJavaScriptライブラリです。

たとえば、以下のようにCDNから読み込むだけで、スライダー+サムネイル+ナビゲーションといった複数機能を持つスライダーがすぐに動作します。

  <!-- Swiper JS -->
  <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>

  <!-- Initialize Swiper -->
  <script>
    var swiper = new Swiper(".mySwiper", {
      spaceBetween: 10,
      slidesPerView: 4,
      freeMode: true,
      watchSlidesProgress: true,
    });
    var swiper2 = new Swiper(".mySwiper2", {
      spaceBetween: 10,
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
      thumbs: {
        swiper: swiper,
      },
    });
  </script>

npmインストールに変更した時にハマった

CDNや配置したアセットを読み込む場合は問題なく動作しますが、npmからSwiperをインストールして、以下のようにインポートして使おうとすると、

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

const swiper = new Swiper(...);

……スライダー自体は表示されても、ナビゲーションやサムネイル連動、自動再生といった機能がまったく動作しなくなってしまいます。

Swiperはモジュール制になっている

ドキュメントにもちゃんと書いてあるのですが、

By default Swiper exports only core version without additional modules (like Navigation, Pagination, etc.).

npm経由で使う場合は、必要な機能を明示的にインポートする必要がありました。

必要な機能を個別に読み込む

// core version + navigation, pagination modules:
import Swiper from 'swiper';
import { Navigation, Pagination } from 'swiper/modules';
// init Swiper:
const swiper = new Swiper('.swiper', {
  // configure Swiper to use modules
  modules: [Navigation, Pagination],
  ...
});

全部入りを読み込む

// import Swiper bundle with all modules installed
import Swiper from 'swiper/bundle';

ドキュメントをきちんと読めば書いてあることではありますが、読まずに時間を無駄にしてしまいました。
npmで使う際は、モジュール構成に注意して、必要な機能を忘れず読み込むようにしましょう。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?