Installing Bootstrap 4 on Rails 6
Bootstrap is a front-end web framework that makes creating responsive web layouts and interactive front-end components far easier than it was years ago. While it’s not the only front-end, responsive, mobile-first framework these days, it is arguably the most popular. It also pairs well with Ruby on Rails. In this post, we’ll explore how to install Bootstrap 4 on Rails 6.
Because Bootstrap 4 depends on jQuery for its various interactive elements (tooltips, popups, modals), we need a way to install jQuery and have it compile through webpack. In Rails 5, this was usually done using Ruby gems for Bootstrap and jQuery.
In Rails 6, we use yarn to install and import the node modules and then use webpack to run the modules. A new Rails 6 app will have webpack installed by default through the webpacker gem when a new Rails app is created.
First, let’s create a new Rails app called bootstrapper:
Now let’s cd into the new bootstrapper directory and install Bootstrap and its dependencies jQuery and popper.js which is used for tooltips, popovers, dropdowns and modals:
Next, to setup Bootstrap the first thing we want to do is to go into the webpack directory’s environment.js file located at config/webpack/environment.js and add the new Provide plugin for webpack. Note that the top and bottom lines are already in the file. We just need to add the code block in the middle:
Then, inside the newly created application.scss file, add the following import statement:
Creating Our Test Controller, Views & Routes
Let’s test our Bootstrap installation by creating a controller called post with an index action which will also create our post index view:
The Rails controller generate statement above also created a route for us in the config/routes.rb file so let’s edit that file to make the post index view our root:
Now we are ready to start adding Bootstrap components. Let’s add the standard Bootstrap navbar by grabbing the example navbar component code from the Bootstrap website and pasting it into our layout file app/views/layouts/application.html.erb.
Underneath the navbar code we can also add the example tooltip component code to test that functionality as well:
Now, all we need to do is start our local dev server by typing in rails s at the command line from inside our application directory, open our browser and navigate to http://localhost:3000/.
As we can see in the screenshot below, when our page loads both our navbar and tooltips are rendering in the main Bootstrap style which means we have successfully installed Bootstrap 4 in Rails 6: