How to add Bootstrap 4 to Rails 6

Richard Chea
2 min readMay 31, 2020

--

Great, so you’ve got Rails going with your new project but it’s looking pretty bland with just text. Now let’s make it pretty with Bootstrap.

The first thing you’ll want to do is add Bootstrap and it’s dependencies. It will require jQuery and Popper.js and we’ll do this by using Yarn. Go ahead and run the command to add all three.

yarn add bootstrap jquery popper.js

The next step is setting up Rails to recognize Bootstrap. We’ll start by navigating to app/config/webpack/environment.js and add the code below. The first line and last line will already be in the environment.js file so you’ll only have to add the lines in between them.

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

Next, you’ll navigate to app/assets/stylesheets folder and locate the file application.css file. Go ahead and rename your application.css file to application.scss. Then add the line below that file.

@import 'bootstrap';

Now we can test Bootstrap to see if it’s working. We’ll do this by going to Bootstrap’s website, copying the code to create buttons, and adding it to one of our pages. The code is provided below for the button from Bootsrap’s website.

<div class="btn-group" role="group" aria-label="Basic example">   <button type="button" class="btn btn-secondary">Left</button>   <button type="button" class="btn btn-secondary">Middle</button>   <button type="button" class="btn btn-secondary">Right</button></div>

Run your Rails server and load that page where you added the lines for the button creation. You should now see the buttons loaded Bootstrap style.

Head over to the Bootstrap and check out the documentation to bring your site to life with all the neat components built into Bootstrap that you can use. Using Bootstrap will make front-end quicker to build out with all its features.

Resources

Boostrap Documentation — https://getbootstrap.com/docs/4.5/getting-started/introduction/

--

--

No responses yet