【Rails】Webpackerを使ってjQueryとBootstrapを管理する方法

はじめに

本記事では、Rails 6.0から導入された「Webpacker」を使ってjQueryとBootstrapを管理する方法を説明します。

WebpackerでjQueryとBootstrapを管理

Railsアプリの作成

以下のコマンドを実行して、新しいRailsアプリを作成します。コマンド引数に_6.0.0_をつけることで作成するアプリのRailsバージョンを指定することができます。

$ rails _6.0.0_ new test_app

以下のコマンドを実行して、コントローラーとビューを作成します。

$ rails g controller Statics index

テストサーバーを起動しRailsアプリが作成できているか確認してみます。

$ rails s

テストサーバーが起動したら、ブラウザでhttp://localhost:3000/statics/indexにアクセスします。以下のように表示されていればOKです。

jQueryとBootstrapをインストール

以下のコマンドを実行して、jQueryとBootstrapをインストールします。popper.jsはBootstrapのツールチップを使うために必要になります。

$ yarn add jquery bootstrap popper.js

package.jsonにjQueryとBootstrapが追加されていればOKです。

package.json

{
  "name": "test_app",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "^4.2.0",
    "jquery": "^3.4.1",
    "bootstrap": "^4.4.1",
    "popper.js": "^1.16.0",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.9.0"
  }
}

jQueryの管理

app/javascript/packs/application.jsに以下を追記します。

application.js

require("jquery")

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

environments.js

const webpack = require('webpack')

environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

Bootstrapの管理

app/javascript/配下にsrcというディレクトリを作成し、その中にapplication.scssというファイルを作成します。作成したapplication.scssに以下を記述します。

application.scss

@import '~bootstrap/scss/bootstrap';

app/javascript/packs/application.jsに以下を追記します。

application.js

import 'bootstrap'
import '../src/application.scss'

動作確認

確認のため、app/views/statics/index.html.erbを以下のように変更します。ページ読み込み時にjQueryでBootstrapのスタイルを適用させています。

index.html.erb

<h1>Statics#index</h1>
<p>Find me in app/views/statics/index.html.erb</p>

<!-- 以下を追記 -->
<script>
  $(window).on('load', function() {
    $('body').addClass('bg-dark');
    $('body').addClass('text-light');
  });
</script>

テストサーバーを再起動します。

$ rails s

http://localhost:3000/statics/indexにアクセスします。以下のように、ページ読み込み時にBootstrapのスタイルが適用されていればOKです。

ちなみに、Webpacker管理下のファイルが更新されたときはWebpackerのコンパイルが走ります。テストサーバーを起動したターミナルを見てみると、以下のようなログが出力されています。コンパイルに約37秒かかっていることがわかります。

[Webpacker] Compiling...
[Webpacker] Compiled all packs in /Users/user/Products/test_app/public/packs
[Webpacker] Hash: 53154d7baad00c6a1252
Version: webpack 4.41.2
Time: 3718ms

設定ファイル全文

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

// 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)

import 'bootstrap'
import '../src/application.scss'

app/javascript/src/application.scss

@import '~bootstrap/scss/bootstrap';

config/webpack/evironment.js

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

const webpack = require('webpack')

environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

module.exports = environment

まとめ

Rails 6.0から導入されたWebpackerを使ってjQueryとBootstrapを管理する方法を説明しました。参考にしていただければと思います。

関連記事

【Rails】Railsアップグレードまとめ
# はじめに Ruby on Railsに限らず、何らかのフレームワークを使ってWebシステムを構築している場合、フレームワークのアップグレード作業は避けて通れません。 一般的にフレームワークはバージョン毎にEOL (End of Life [...]
2022年10月1日 14:32
【Rails】ユーザー登録時に行うメールアドレス認証機能の実装方法
# はじめに ユーザー登録/解除やログイン/ログアウトといった認証機能の導入に「devise」というGemを使っている人は多いと思います。「devise」では以下のように記述するだけで、ユーザー登録時に確認メールを送付しメールアドレス認証を行う機 [...]
2022年9月24日 14:24
【Rails】モデルに列挙型(enum)を定義し、使いこなす方法
# はじめに Railsはモデルでカラム名と同名の列挙型(enum)を定義することで、カラムと列挙型の変数を紐付けることができます。カラムと列挙型の変数を紐付けると、カラムに対して様々な便利な使い方ができるようになります。 本記事では、モデ [...]
2022年9月3日 10:29
【Rails】RailsでCORSとPreflight requestの設定を行う方法
# はじめに RailsアプリをAPIサーバーとして構築するには、CORS (Cross-Origin Resource Sharing)と Preflight requestの設定を行う必要があります。APIサーバーは外部からの要求に対して処理 [...]
2022年8月27日 10:44
【Rails】M1チップ搭載MacでRuby on Railsの開発環境構築
# はじめに M1チップ搭載MacにRuby on Railsの開発環境を構築する手順を記載します。 - MacBook Air (M1, 2020) - macOS Monterey 12.3.1 # Homebrew ## [...]
2022年5月5日 11:56
【Rails】Rakeタスクの基本情報と作成・実行方法
# はじめに Railsには標準でRakeというGemが同梱されています。RakeはRubyで実装されたMake(UNIX系のOSで使用できるコマンド)のようなビルド作業を自動化するツールです。Ruby Make、略してRakeというわけですね。 [...]
2022年3月7日 22:12
【Rails】モデルに外部キーを設定する方法とよく起こるエラー内容について
# はじめに Railsでモデルに外部キーを設定する方法について説明します。 # モデルに外部キーを設定する ## リレーションシップ 今回は1つのブログ記事は複数のコメントを持つ1対多のリレーションシップを例に説明します。現在は` [...]
2022年2月10日 14:18
【Rails】Capybaraのfill_inメソッドを実行すると「既存レコードの内容+指定した内容」がセットされる事象の原因と対処【RSpec】
# はじめに RSpec + Capybaraを使用して、Railsアプリの統合テストを実装しています。とあるモデルの編集画面において、入力フォームの内容を書き換えた上で送信し、レコードが更新されることを確認します。 入力フォームの内容を書 [...]
2022年1月27日 21:22