Import Bootstrap into a Ruby on Rails 6 Application
In Ruby on Rails August 14, 2021
Updated on May 13, 2023
In this article, we will discuss the steps needed to import the Bootstrap library into a Rails 6 app. We will import the 5.1 version, which is the latest version at the time of writing.
Rails uses Yarn as its package manager, so we’ll install Bootstrap via Yarn. Bootstrap has two parts: the CSS part and the JavaScript part which is used for components such as dropdowns, popovers, or tooltips. Therefore, when importing Bootstrap, we must take care of both. Rails 6 uses Webpacker to manage JavaScript code in our applications and the asset pipeline for CSS and images. That's why we will import the Bootstrap's CSS code into the asset pipeline and let Webpacker manage the Bootstrap's JS code.
Install Bootstrap
Let's get started by installing Bootstrap! Some Bootstrap components depend on the Popper library, so we need to install that as well. From your terminal, change the directory to your Rails application and type the following command:
yarn add bootstrap @popperjs/core
It will install the latest version of these libraries.
Import Bootstrap's CSS
Now, we need to import the Bootstrap's CSS. This will be imported into our application.css
file in the
app/assets/stylesheets/
folder. This is the CSS manifest file in a typical Rails application. Our
Bootstrap code was installed in the node_modules/
folder by Yarn. So we're going to refer to that folder,
more specifically we're going to refer to the minified version of the Bootstrap CSS library. It can be found in the
node_modules/bootstrap/dist/css/
directory. After the require statements, we just need to add this
statement:
@import 'bootstrap/dist/css/bootstrap.min.css';
Import Bootstrap's JavaScript
We are finished with the CSS, but we need the JavaScript, too. We need to import the Bootstrap JS files into our pack
application
. In Rails, we put these packs that are automatically compiled by Webpack in the
app/javascript/packs/
folder. The pack application
we use is generated when the application
is created. All we have to do is add this line after the other import statements:
import * as bootstrap from 'bootstrap'
It will get all the named exports.
Initialize Tooltips
To use tooltips, we must initialize them first. From the Bootstrap
documentation site, we learn that one way we can do this is to enable all tooltips on a page. So all we
have to do is add this code at the bottom of the app/javascript/packs/application.js
file:
window.addEventListener('turbolinks:load', () => {
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
})
That was all we had to do to have access to the Bootstrap classes and start styling our pages.