LoginSignup
0
0

More than 3 years have passed since last update.

RailsでBootstrapを使用する時に特定のパーシャルを抜き出して使う

Posted at

はじめに

Railsアプリケーションを開発する中でBootstrapすべてではなく、特定のパーシャルファイルをapplication.scssにインポートする際にハマったので残しておきます。

合わせて読んでいただけそうな記事

以前に私が書いた以下の記私が毛色は似ているのですが、今回は別の記事として記載します。
ぜひこちらもご覧下さい。
RailsでBootstrapのグリッドシステムのみを使用する

環境

Ruby 2.7.2
Ruby on Rails 6.0.3.4

前提

以下を実行してYarnにbootstrapが追加済みであること

$ yarn add bootstrap 

ハマった部分

今回の要件で、アプリケーション内のヘッダーの部分のみBootstrapを使用できるようにしたいという話がでたのでapplication.scssに以下のように追記をしました。

app/assets/stylesheets/application.css
省略

@import "bootstrap/scss/nav";
@import "bootstrap/scss/navbar";

rails sでサーバーを起動してhttp://localhost:3000/にアクセスしましたが、以下のエラーが画面に出力されてしまいました。

We're sorry, but something went wrong.

logをみると以下のように出力されていたので、ビューファイルを確認するが追記はしていないので怪しい部分は見当たらず。。

  Rendered collection of homes/_notification.html.erb [0 times] (Duration: 0.0ms | Allocations: 3)
  Rendered homes/index.html.erb within layouts/application (Duration: 3.3ms | Allocations: 1221)
Completed 500 Internal Server Error in 33ms (ActiveRecord: 2.6ms | Allocations: 10983)

解決方法

  • まずはエラーが出るまでの変更箇所を確認する
  • 追記したファイルで怪しい部分の割り出し(今回の場合はapplication.scss)
  • 実際にコメントアウト等をして再起動してみる
  • 対象箇所がわかったら原因の追求

仮設 その1

Bootstrapを導入したことによる影響か?
yarn add bootstrapでyarnに追加しただけなので、恐らくエラーとは違う

仮設 その2

application.scssのimport部分の記述が足りない・もしくは間違っているのか?

今回は 仮設の2番が正解でした。
bootstrapで特定のパーシャルファイルをインポートする際の方法を調べます。

結果

bootstrapで特定のパーシャルファイルを抜き出して使用するためには、以下の部分が必要でした。
どうやら最低限のパーシャル部分が必要になるようです。

変更前

app/assets/stylesheets/application.css

@import "bootstrap/scss/nav";
@import "bootstrap/scss/navbar";

変更前

app/assets/stylesheets/application.css
#必須パーシャル
@import "bootstrap/scss/functions";
@import "bootstrap/scss/variables";
@import "bootstrap/scss/mixins";

@import "bootstrap/scss/nav";
@import "bootstrap/scss/navbar";

普段Bootstrapを使うときはどうしてもテンプレートでbootstrap.scssをインポートしてしまうので良い機会になりました。

参考記事

Bootstrap 4 CSS customization

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