LoginSignup
6
5

More than 3 years have passed since last update.

RailsにBootstrapを導入!!

Posted at

RailsにBootstrapを導入する方法を説明致します。
手順は、とても簡単ですのでご参考にどうぞ!!
手順は、4つあります。

手順

1.Bootstrapのインストール
2.SCSSファイルの作成
3.JSファイルの修正
4.Rails(Puma)の再起動

1.Bootstrapをgemでインストール

RailsでBootstrapを使う場合は、gemを使ってインストールする方法が一般的です。
Bootstrapは内部でjQueryを利用しているので、こちらもあわせてインストールしましょう。
Gemfileに以下を追記して、bundle installを実行してみてください。

Gemfile
gem 'bootstrap', '~> 4.3.1'
gem 'jquery-rails'
ターミナル
% bundle install

2. SCSSファイルを作成

次に、application.cssをapplication.scssというファイル名に変更します。
これは、Bootstrapが「SCSS」という記法で書かれており、Railsでもあわせて利用するためです。
「SCSS」とは、CSSを拡張した記法のことで、いまのWeb業界では多く利用されている記法になります。
ここでは具体的な解説はしませんが、CSSの記述よりも見やすく、書きやすくなった記法だと思ってください。

ファイルの拡張子を変更
 変更前 app/assets/stylesheets/application.css 
 変更後 app/assets/stylesheets/application.scss

ファイル名を変更したら、実際にファイルを開いて下さい。
*= require_tree .と*= require_selfを削除し、
@import "bootstrap";を追記します。

追記したコードが、Bootstrapを読み込むための設定になります。

app/assets/stylesheets/application.scss
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's
 * vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
 * files in this directory. Styles in this file should be added after the last require_* statement.
 * It is generally better to create a new file per style scope.
 *
 *= require_tree .    <(削除)
 *= require_self      <(削除)
 */
@import "bootstrap";  <(追加

3. JSファイルを修正

Bootstrapで使われる「JavaScript」や「jQuery」などの関連ファイルを読み込む設定をします。
app/assets/javascripts/application.jsを開き、以下を参考に元々あったコードの上に追記してください。

app/assets/javascripts/application.js
# 以下の3つを追記
//= require jquery3
//= require popper
//= require bootstrap

# 元々あったコード
//= require rails-ujs
//= require activestorage
//= require turbolinks

4. Rails(Puma)を再起動

ここで一度、ブラウザからアクセスしてみてください。
もし、この段階でエラーが表示されているのであれば、Rails(Puma)を再起動します。
それでもエラーが変わらない場合は、「node.js」のバージョンが古い可能性があります。
DockerでRailsを構築した方は、Dockerfileが以下のような設定になっているかを確認してください。

Dockerfile
# Railsに必要なパッケージをインストール
RUN apt-get update -qq && apt-get install -y nodejs
RUN curl -sL https://deb.nodesource.com/setup_10.x | bash - \
    && apt-get install -y nodejs

# 以下の公式サイトの記述ではnode.jsのバージョンが低くてbootstrapが使えない
# RUN apt-get update -qq && apt-get install -y nodejs

まとめ

導入手順は難しいと思うかもしれませんが、この説明した手順の通りに記述を削除したり、
書き換えたりするだけですので意外と簡単です。
是非試してみて下さい!!

以上。

6
5
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
6
5