Once again - Rails 6, Webpacker, jQuery and Bootstrap tutorial

Rails Apr 22, 2020

Tricky? Not working? Confusing? Invest couple minutes on this article and get it work in couple of minutes.

I know, there is loads and loads of these articles around internet and yet I am writing one to make that pile taller. Thing is, some articles are written before Rails 6 was officially released and in some cases that information may be a bit confusing. I am now writing one more article on this topic since so many have asked me how to do it.

How to do it

Step 1 - Create new rails app:

rails new r6_webpack_jquery_bs_tutorial --skip-turbolinks

I skipped turbolinks, let's keep this all as minimum as possible.

Step 2 - Use Yarn to add Bootstrap, jQuery and Popper

yarn add bootstrap jquery popper.js

Step 3 - Add bootstrap styles

Rename: app/assets/application.css to app/assets/application.scss (basically just css extension to scss)

Clear your application.scss file and add @import 'bootstrap/scss/bootstrap'; to top of file.

Step 4. Bootstrap and enable tooltips

Open up app/javascripts/packs/application.js

at end of file, add:

import "bootstrap"
$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

Step 5. Add jQuery to webpacker environment

Open file config/webpacker/environment.js

There should be only two lines, starting with const... and file ending with module.exports..., between those lines add:

const webpack = require('webpack')
environment.plugins.append('Provide', new webpack.ProvidePlugin({
  $: 'jquery',
}))

Step 6. Create simple view to see it really works

Punch in rails g controller Home index and open app/views/home/index.html

<button type='button' data-toggle='tooltip' title="This is fancy tooltip if jQuery works">
  Hover over this button
</button>

If you see nice tooltip, jQuery and Bootstrap works just fine. If you see simple HTML tooltip (small text, everything in one line) then you did something wrong, jump to step 1 and double check.

Then just rails s and check http://localhost:3000/home/index

Word about jQuery and Bootstrap

While writing this there is currently small issue with Bootstrap 4.4.1 and jQuery 3.5.0. If you are having problems with collapse on your page, check this out:

https://github.com/twbs/bootstrap/issues/30553

To solve this problem, use different version combination. See your package.json.

Mika Peltomaa

Full Stack Hero who is not afraid to step out from comfort zone. Developing apps for web and mobile is close to heart, including Game Development as a Weekend Warrior.

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.