0
0

More than 1 year has passed since last update.

Rails6にBootstrapを導入する際に嵌ったこと

Posted at

どうも。
Railsアプリの開発で、Bootstrapがうまく反映されない問題が発生したため、
再発防止を兼ねてメモ。

  • 事象
    Rails6のアプリを作成時にBootstrapを導入しようとし、以下のプログラムを編集したものの、Bootstrapが反映されなかった。
/funyuspaceapp01/app/javascript/packs/application.js
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//= require jquery
//= require jquery_ujs
require('articles')
require('../images', true)

import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"
import "bootstrap"
import "../stylesheets/application"

Rails.start()
Turbolinks.start()
ActiveStorage.start() 
/funyuspaceapp01/app/javascript/stylesheets/application.scss
@import "~bootstrap/scss/bootstrap.scss";
(以下、bootstrapの中身の定義)
  • 対策①
    下記のファイルを変更
(変更前)/funyuspaceapp01/app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>Funyuspaceapp01</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>
(変更後)/funyuspaceapp01/app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>Funyuspaceapp01</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

(参考)https://teratail.com/questions/289925
→効果なし

・対策②
コンソール画面のエラー
「application.js:1 Uncaught Error: Cannot find module 'bootstrap'」
より、BootstrapのJavaScriptライブラリを、アプリケーションにインストールできていないのでは?と推察

boostrap5バージョンをインストール
yarn add bootstrap@5.0

→無事導入されました。

(追記)
ドロップダウンなどのポップアップ要素をいい感じにしてくれるpopper.jsもインストールすると良いらしいです。
yarn add @popperjs/core

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