Help us understand the problem. What is going on with this article?

Rails5.1 + Webpacker で Bootstrap4-beta を読み込む

More than 1 year has passed since last update.

JS と CSS を Webpacker 管理にする場合に、
Bootstrap を読み込む際にハマったのでメモする。

環境

  • Rails : 5.1.4
  • Webpacker : 3.0.2
  • Bootstrap : 4.0.0-beta

Webpacker の導入

Gemfile
gem 'webpacker'
$ bin/bundle
$ bin/rails webpacker:install

rails new する時に導入することもできる。

# Available Rails 5.1+
rails new myapp --webpack

Bootstrap の導入

$ yarn add bootstrap@next

現在(2017/10/13) は、 next タグをつけることで 4.0.0-beta を指定できる。

Bootstrap を 読み込む

ディレクトリ構成

app/javascript/
├── packs
│   └── application.js
└── src
    └── application.scss
app/javascript/packs/application.js
import 'src/application' // application.scss の読み込み
import 'bootstrap/dist/js/bootstrap'
app/javascript/src/application.scss
@import '~bootstrap/dist/css/bootstrap'
app/views/layouts/application.html.haml
= javascript_pack_tag 'application'
= stylesheet_pack_tag 'application'

jQuery と Popper.js を読み込む

Bootstrap4.0.0-beta では、 jQuery と Popper.js が必要。

yarn add jquery
yarn add popper.js

jQueryPopper がグローバル変数として参照できないと、
Bootstrap のエラーが console.log に吐かれて正常に読み込まれない。

config/webpack/environment.js
const { environment } = require('@rails/webpacker')
const webpack = require('webpack')

environment.plugins.set( // Webpacker 3.3.0 以降は set ではなく prepend を使用する
  'Provide',
  new webpack.ProvidePlugin({
    jQuery: 'jquery/dist/jquery',
    Popper: 'popper.js/dist/popper'
  })
)

module.exports = environment

追記

webpackerを使ったrailsアプリを実行するとき、TypeError: environment.plugins.set is not a functionというエラーが出る - Qiita によると、 Webpacker 3.3.0set が remove されたらしいので、 environment.plugins.set ではなく environment.plugins.prepend を使うと良いみたいです。

ビルド

bin/webpack-dev-server でビルドし、変更を自動でブラウザに反映してくれる。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away