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にBootstrapとStimulusを導入する

Last updated at Posted at 2025-10-18

バージョン

rails 8.0.3
Bootstrap 5.3.x
stimulus-rails 1.3.4

動機

それなりに苦労したので。
Webにいろいろ情報があったが錯綜ぎみなので整理しておく。

Bootstrap

gem bootstrapを使う」との情報が多いが、そのままでは動作しなかったのと、依存gemを減らしたかったので手動で導入した。

app/views/layouts/application.html.erb

単純にlinkタグを記載する。

<html>
  <head>
    ...
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap. min.css" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB"   crossorigin="anonymous">

config/importmap.rb

ESM版のURLを記載する。これによりapp/views/layouts/application.html.erbjavascript_importmap_tagsヘルパーで読み込まれる。
Bootstrapは@popperjs/coreに依存しているので先にPopperを先に記載する。

pin "@popperjs/core", to: "https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/esm/popper.min.js"
pin "bootstrap",      to: "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.esm.min.js"

Stimulus

rails stimulus:installを実行すると使えるようになるが、いじくり回してたら動かなくなったので、構成を理解して手動でも導入できるようにした。

config/importmap.rb

toで指定しているファイルはgems/stimulus-rails-1.3.4/app/assets/javascriptsのものが使われる。最後のpin_all_fromapp/javascript/controllers配下のモジュールを使用するための設定。

pin "@hotwired/stimulus", to: "stimulus.min.js"
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js"
pin_all_from "app/javascript/controllers", under: "controllers"

app/javascript/application.js

app/javascript/controllers配下のモジュールを読み込む。

import "controllers"

app/javascript/controllers/application.js

gems/stimulus-rails-1.3.4/lib/install/app/javascript/controllers/application.jsをコピー。

app/javascript/controllers/index.js

gems/stimulus-rails-1.3.4/lib/install/app/javascript/controllers/index_for_importmap.jsをコピー。

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?