Rails 7 Bootstrap With Sprockets

Now that webpacker is no longer the preferred way to bundle CSS in Rails, here’s a quick proof-of-concept for using Bootstrap 5 in Rails 7 delivered through Sprockets and Webpacker.

The only reason you need to do this is that Boostrap is a very old technology and is not engineered around the new importmap paradigms introduced with Rails 7.

If this is you, or if you need to have jQuery globally available as-in the pre-2015 web development days, this tutorial is for you. We will be installing Bootstrap using both Sprockets (for the CSS) and Webpacker (for the Javascript)

rails new MyGreatApp --pre

gem 'bootstrap', '~> 5.1.0'


Also uncomment the scss-rails Gemfile:

gem "sassc-rails", "~> 2.1"

And bundle install

Then delete this file:

Now make a new file called application.scss in the same folder app/assets/

Here you add:

@import "bootstrap";

Add a dummy navbar to your home page and it should look like this:

OPTION A: Using Webpacker (Recommended)

However, notice that the hamburger menu does not work. That’s because we haven’t yet added Javsacript

However, even though we’ve added Bootstrap with Sprockets I’m going to still add jQuery using Webpacker, like so:

Add to the Gemfile

gem 'webpacker'

Then run rails webpacker:install

Check these files in your repo.

Then add jQuery using yarn:

yarn add jquery

Now you’ll go to config/webpack/environments.js and add this content between the existing content, above the line module.exports = environment

const webpack = require('webpack')
environment.plugins.prepend('Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery'
})
)

Now you’ll need to make a new file at javascript/packs/webpack.js:

require('jquery/src/jquery.js')

Rails 7

Remember, you’ve left your normal Rails-default javascript/application.js file (which is no longer related to webpacker), as the default:

import "@hotwired/turbo-rails"
import "controllers"

Then confirm that jQuery is working by opening the browser window to your app, opening the developer tools

Option B: Using Importmap (New for Rails 7)