How to add Bootstrap 5 to your Rails 6 application

If you are developing a Rails application you may want to add styles to make it more visually appealing. One way to do this is to use Bootstrap, an HTML, CSS, and JavaScript framework that makes it easier to make responsive and mobile-friendly web projects. You may incorporate Bootstrap's layout principles and components into your Rails application to make user interactions with your site more engaging by using it in a Rails project.

To add Bootstrap 5 to your application;

Navigate to your terminal and run the following command yarn add bootstrap@next jquery @popperjs/core

You should see the following output in your terminal

installdependencies.png

Many of Bootstrap’s components require JQuery and Popper.js, along with Bootstrap’s own custom plugins, so this command will ensure that you have the libraries you need.

Next is to go to your webpack configuration file which is found in the following path config/webpack/environment.js and make the following changes.

const { environment } = require('@rails/webpacker')
const webpack = require("webpack") 

environment.plugins.append("Provide", new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  Popper: ['popper.js', 'default']
}))

module.exports = environment

The ProvidePlugin helps us avoid the multiple imports or require statements we would normally use when working with JQuery or Popper modules. With this plugin in place, webpack will automatically load the correct modules and point the named variables to each module’s loaded exports.

Next, navigate to app/javascript/packs/application.js which is your webpack entry point and add import statements to import your bootstrap and stylesheets file.

import "bootstrap"
import "../stylesheets/application" # This is your stylesheet file where you will write all the styling code.

If you are yet to create the stylesheet file, run the following command in your terminal mkdir app/javascript/stylesheets Create a new file called application.scss

Inside this file, you can now add your styling code but first start with adding this line at the top of the file

@import "~bootstrap/scss/bootstrap";

Thank you for reading