Getting Bootstrap working with Webpack

Rails 6 introduced webpacker, which they encourage use of now over the legacy asset pipeline. This article explains how to get bootstrap, which is used by almost all applications, working with webpacker in Rails 6.

First, run the command:

1
yarn add bootstrap jquery popper.js

Now in environments.js, add the following code:

1
2
3
4
5
6
7
8
9
10
11
12
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

In app/javascript/packs/application.js import bootstrap.

1
import 'bootstrap'

Now create application.scss in app/javascript/packs/src and import bootstrap there.

1
@import '~bootstrap/scss/bootstrap'; 

Lastly, import this application.scss in the application.js.

1
import './src/application.scss'

Now you have successfully added bootstrap to your Rails 6 project. Happy bootstrapping!