0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Rails] Swiper v.11.1.14の導入方法

Posted at

はじめに

この記事は、以下のような方を対象としています。

  • RailsアプリにCDNでサクッとSwiperを導入したい方
  • SwiperをyarnでDockerコンテナ内に入れ、ブラウザ上で扱いたい方

また、この記事の説明はSwiperの導入までなので、具体的なスライド機能の実装方法などは扱っておりません。 その点ご了承くださいませ。

補足

実装方法(HTMLレイアウトやスタイル)は、公式ページに詳しく載っているのでそちらをご覧ください。

Swiperとは?

Swiperは、画像スライダーやカルーセルを直感的に実装でき、多彩なスライド効果(ループ・自動再生・フェード等)を表現できる軽量かつ高機能なjQueryプラグインです。

開発環境

  • macOS: Sequoia 15.1.1
  • Ruby: 3.1.4
  • Rails: 7.0.4
  • Docker
  • yarn

導入方法

CDNから読み込む方法が最も簡単です。
ただ、yarnなどパッケージマネージャで管理したい方は、Swiperを(今回はDockerコンテナ内に)インストールし、ブラウザ上で利用するためにいくつか設定する必要があります。

方法1: CDNの利用

公式ページの通りレイアウトファイルにコピペするだけで使用できます。
今回はslimファイルに記述する方法を書いておきます。

app/views/layouts/application.html.slim
doctype html
html
  head
    .
    .
    .
+   = stylesheet_link_tag "https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css"
    = javascript_include_tag 'application'
+   = javascript_include_tag "https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"

方法2: yarnでインストールする方法

1. yarnでDockerコンテナ内にインストール

1-1. コンテナを起動

docker compose up

1-2. コンテナ内でSwiper v.11.1.14をインストール

docker compose exec web yarn add swiper@11.1.14

結果

  • node_modules/swiperが追加されていることを確認

  • 特に、この後node_modules/swiper/swiper-bundle.cssnode_modules/swiper/swiper-bundle.jsを参照するので、要確認
    スクリーンショット 2025-05-23 17.26.01.png

  • package.jsonにSwiper v.11.1.14が追加されていることを確認

package.json
{
  "name": "app",
  "version": "1.0.0",
  "engines": {
    "node": ">=12.14.0"
  },
    .
    .
    .
  "dependencies": {
	.
	.
	.
+   "swiper": "11.1.14"
  }
}

2. node_modules下にあるSwiperをブラウザ上で使えるように設定する

2-1. アセット設定ファイルの設定

node_modules下にあるパッケージ(今回の場合はSwiper)をアセットパイプラインが読み込めるように設定する

config/initializers/assets.rb
+ Rails.application.config.assets.paths << Rails.root.join('node_modules')

2-2. javascript読み込み設定

マニフェストファイルでnode_modules/swiper/swiper-bundle.jsを参照する

app/assets/config/manifest.js
//= link_tree ../images
//= link_tree ../builds
//= link application.css
//= link application.js
+ //= link swiper/swiper-bundle.js
  • linkディレクティブを使用して、swiper/swiper-bundle.jsを独立したアセットとして扱うように指示する

レイアウトファイルでマニフェストファイルで指定されたswiper/swiper-bundle.jsを読み込む

app/views/layouts/application.html.slim
doctype html
html
  head
	.
	.
	.
    = javascript_include_tag 'application'
+   = javascript_include_tag 'swiper/swiper-bundle.js'

2-3. css読み込み設定

node_modules/swiper/swiper-bundle.cssを読み込む

app/assets/stylesheets/application.scss
+ @import "swiper/swiper-bundle";

参考資料

この記事で扱わなかった参考資料はこちらです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?