Add Bootstrap 5 to a Rails 6 App
Published: 2020-12-19
Intro
In this post I will show you how to add the Bootstrap CSS framework to your Rails 6 application.
Bootstrap is a solid CSS framework that allows us to make our app look really nice and work across a multitude of device types and browsers without having to get bogged down in the details.
Software
The following software versions were used in this post.
- Rails - 6.0.3.4
- Popper.js - core/2.5.4
- Bootstrap - 5.0.0-beta1
Installation
Add the popper.js and bootstrap packages through yarn.
yarn add @popperjs/core@^2.5.4
yarn add [email protected]
Add the stylesheet_pack_tag tag to the views/layouts/application.html.erb file in the <head></head> section.
<%# views/layouts/application.html.erb %>
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
Also, remove the stylesheet_link_tag tag from the same views/layouts/application.html.erb file.
<%# views/layouts/application.html.erb %>
<%# Delete me %>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
In the app/assets/stylesheets/application.css file add the following contents.
/* app/assets/stylesheets/application.css */
/* import the bootstrap library */
@import "bootstrap"
/* import other css files below. */
In the app/javascript/packs/application.js file, add the following contents at the end.
// app/javascript/packs/application.js
// import the bootsrap library.
import "bootstrap;"
// import the app/assets/stylesheets/application.css
// file from the previous step.
import "../../assets/stylesheets/application;"
Now restart your server and fingers crossed you should be good to go.
Usage
For detailed usage, check the docs, But as an example, to add a nicely styled button, add the bootstrap CSS classes to the tag.
<button type="button" class="btn btn-primary">Primary</button>
Outro
In this post we added Bootstrap 5 to our Rails 6 application. Behold the beauty of Bootstrap 5.
Links
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://medium.com/daily-web-dev/use-bootstrap-4-with-ruby-on-rails-6-and-webpack-fe7300604267
https://blog.makersacademy.com/how-to-install-bootstrap-and-jquery-on-rails-6-da6e810c1b87
https://medium.com/@coorasse/goodbye-sprockets-welcome-webpacker-3-0-ff877fb8fa79