Rails6にBootstrapを導入する

RailsにBoostrapを導入する際はWebpackerを使います。

Webpackerとは、複数のJavaScriptファイルなどを1つにまとめて出力するツールであるwebpackを簡単にRailsアプリケーションに統合できるGemです。

以下のコマンドでBootstrapを入れましょう。

yarn add jquery bootstrap popper.js

Bootstrapでは、いくつかのコンポーネントで jQuery, Popper.js といった JavaScript のプラグインが必要なため一緒にインストールします。

config/webpack/environment.jsに以下のコードを追記します。

const { environment } = require('@rails/webpacker')

module.exports = environment

const webpack = require('webpack')
environment.plugins.append(
  'Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Popper: ['popper.js', 'default']
  })
)

Boostrapのstyleをimport

mkdir app/javascript/stylesheets
touch app/javascript/stylesheets/application.scss

app/javascript/stylesheets/application.scssに以下のコマンドを追加します。

@import '~bootstrap/scss/bootstrap';

app/javascript/packes/application.jsに以下のコードを追加します(一番上の2行)

import 'bootstrap';
import '../stylesheets/application';


// 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("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")


// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

レイアウトに stylesheet_pack_tag を追加

app/views/layouts/application.html.erb<head></head>内に以下のコードを追加します。

<%= stylesheet_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

以上でBootstrapの導入は終了です。