Rails 7 with Bootstrap

How to set up Rails 7 with Bootstrap

This article covers six easy steps for installing Bootstrap in a Rails 7 app.

Whenever I need to start a new project, I forget this and have to search the Internet; somehow, there are no direct-to-the-point articles covering it 🤷‍♂️.

Well, now there is 😎

6 steps to set up Rails 7 with Bootstrap

  1. Install the required gems
  2. Rename application.css file
  3. Import Bootstrap CSS
  4. Configure the Assets initializer
  5. Configure Importmaps for Bootstrap and Popper
  6. Import Bootstrap and Popper JS

1. Install the required gems

Once you have the Rails 7 app ready to go, add the three following gems to your Gemfile:

# Gemfile
gem "sassc-rails"
gem "bootstrap"
gem "mini_racer"

sassc-rails – will be used to compile the SASS files.
bootstrap – will provide three dependencies: bootstrap.css, bootstrap.js, and popper.js.
mini_racer – is a JS runtime that will be needed to compile the assets, especially in the production environment for the command rails assets:precompile | *You can skip this if you already have another JS runtime in your environment.

2. Rename application.css file

Rename the application.css file to application.scss.

# from
# app/assets/stylesheets/applications.css
# to
# app/assets/stylesheets/applications.scss

$ mv app/assets/stylesheets/applications.css app/assets/stylesheets/applications.scss

This will allow the next step: import bootstrap CSS in SASS format.

3. Import Bootstrap CSS

Edit the application.scss file.

# app/assets/stylesheets/application.scss

@import "bootstrap";

4. Configure the Asset initializer

Add bootstrap.min and popper.js to the Assets initializer.

# config/initializers/assets.rb

Rails.application.config.assets.precompile += %w(bootstrap.min.js popper.js)

This will make both files available in the production environment, allowing the next step.

BTW: Popper.js is a Bootstrap dependency and comes with the Bootstrap gem.

5. Configure Importmaps for Bootstrap and Popper

Add bootstrap and popper to the Importmap file.

# config/importmap.rb

pin "bootstrap", to: "bootstrap.min.js", preload: true
pin "@popperjs/core", to: "popper.js", preload: true

6. Import Bootstrap and Popper JS

Edit the application.js file.

# app/javascript/application.js

import "@popperjs/core";
import "bootstrap";

This will import Popper.js and Bootstrap.js into the application.js and make these available in your app.

Conclusion

Considering your layout file already has the tags that insert the application.scss and application.js, your app should be ready to use Bootstrap.

In the DEV environment, it will be loaded automatically; in the PRODUCTION environment, it will be compiled as usual by the rails assets:precompile command.

Was it useful for you?

If yes, consider following me on Twitter at @renatonitta.

And feel free to drop a comment or question below 👊.

Comments