Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bootstrap to Rails 6 with webpacker

Step 1:

Add bootstrap and its dependencies:

yarn add bootstrap jquery popper.js

Step 2:

in config/webpack/environment.js add the following:

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

Step 3: [Bootstrap JS]

In app/javascript/packs/application.js import bootstrap by adding the following:

# app/javascript/packs/application.js
import 'bootstrap'

Optionally, we can add some code to enable tooltips and popover:

document.addEventListener("turbolinks:load", () => {
  $('[data-toggle="tooltip"]').tooltip();
  $('[data-toggle="popover"]').popover()
})

Step 4: [Bootstrap CSS]

Create a folder stylesheets under app/javascript. Inside it we will create the main application.scss file to store our css library imports:

mkdir app/javascript/stylesheets  
touch app/javascript/stylesheets/application.scss

Import bootstrap into that file:

# app/javascript/stylesheets/application.scss
@import "~bootstrap/scss/bootstrap";

And import this file into the js manifest:

# app/javascript/packs/application.js
import '../stylesheets/application'

Step 5:

Tell Rails to start using Webpack. To do that, open the application.html.erb file and make the following change to it.

# app/views/layouts/application.html.erb
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>  
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

We can still keep the asset pipeline working if we had old code depending on it:

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>  
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

Step 6: [Optional]

Include Asset Pipeline Into Webpack update config/webpacker.yml to be able to resolve assets stored in the app/assets folder.

resolved_paths: ['app/assets']

More detailed steps:

Tutorial 1

Tutorial 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.