The best way to install and manage Bootstrap in a Rails application is to integrate it using a modern, maintainable, and flexible approach that leverages the Rails asset pipeline and facilitates future updates and customizations. Here are two widely-used methods:
This method allows you to easily integrate Bootstrap with the Rails asset pipeline and manage updates through Bundler. It’s simple and Rails-friendly, as it integrates with the asset pipeline and easy to update via bundle update, but it may lag behind in supporting the latest Bootstrap features or updates compared to npm packages.
Steps:
gem ‘bootstrap’, ‘~> 5.3.0’
gem ‘sassc-rails’, ‘~> 2.1’ # For SASS support
@import “bootstrap”;
Make sure the file has .scss extension (or .sass for Sass syntax). If you have just generated a new Rails app, it may come with a .css file instead. If this file exists, it will be served instead of Sass, so rename it.
//= require popper
//= require bootstrap
Popper.js is necessary because Bootstrap relies on it to position interactive elements such as dropdowns, tooltips, and popovers. Without it, these components may not function correctly.
This approach gives you more flexibility and control, especially if you need to customize Bootstrap or keep up with the latest updates. This approach works with Rails 5.1+, Rails 6 and Rails 7. For Rails 7, If you’re using esbuild or import maps instead of Webpacker, you’ll need to adjust the way dependencies are managed and imported, as these tools handle JavaScript bundling and asset management differently. It’s easier to stay up-to-date with the latest Bootstrap releases using this approach, and it offers greater control over customization, as well as the ability to eliminate unused parts of Bootstrap through tree-shaking. However, the setup is slightly more complex compared to the gem-based approach.
Steps:
yarn add bootstrap jquery @popperjs/core
# OR
npm install bootstrap jquery @popperjs/core
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
@import “bootstrap/scss/bootstrap”;
import ‘bootstrap’;
<%= stylesheet_link_tag ‘application’, media: ‘all’, ‘data-turbolinks-track’: ‘reload’ %>
<%= javascript_pack_tag ‘application’, ‘data-turbolinks-track’: ‘reload’ %>
If you prioritize simplicity and Rails integration, use the gem-based approach. For flexibility, modern JavaScript workflows, and easier upgrades, opt for the npm/Yarn method. Both approaches can handle customizations efficiently, but npm/Yarn offers more control and future-proofing.