Skip to content

Instantly share code, notes, and snippets.

@bazzel
Last active May 26, 2021 04:20
Show Gist options
  • Save bazzel/2c64e2e5804077f9a61938a93ed54823 to your computer and use it in GitHub Desktop.
Save bazzel/2c64e2e5804077f9a61938a93ed54823 to your computer and use it in GitHub Desktop.
Rails 6 and Bootstrap 4

This blogpost shows how to setup Rails 6 with Bootstrap 4.

This snippet shows a somehow different and less customized approach.

$ rails new rails6-bootstrap4
$ bundle --binstubs
$ yarn add bootstrap jquery popper.js expose-loader
// config/webpack/environment.js

// Make $ available on the window object
// for SJR views and jQuery plugins
// that may expect `$` to be globally available.
environment.loaders.append('expose', {
  test: require.resolve('jquery'),
  use: [
    {
      loader: 'expose-loader',
      options: 'jQuery',
    },
    {
      loader: 'expose-loader',
      options: '$',
    },
  ],
});
// app/javascript/packs/application.js

import $ from 'jquery';
import 'bootstrap/dist/js/bootstrap';

$(document).on('turbolinks:load', function() {
  $('body').tooltip({
    selector: '[data-toggle="tooltip"]',
    container: 'body',
  });

  $('body').popover({
    selector: '[data-toggle="popover"]',
    container: 'body',
    html: true,
    trigger: 'hover',
  });
});
// app/javascript/packs/styles.scss

@import '~bootstrap/scss/bootstrap';
# config/webpacker.yml

...
extract_css: true
# app/views/layouts/application.html.erb

<%= stylesheet_pack_tag 'styles', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
...
<body>
  <div class='container'>
    <%= yield %>
  </div>
</body>
$ bin/webpack-dev-server
$ bin/rails s

I recently found this article that seems to do the same, but a bit more explanation. Worth reading!

@radubogdan
Copy link

radubogdan commented Aug 25, 2020

Thanks for sharing. I have few considerations @bazzel

  1. looks like bootstrap is including jquery, I guess it will work only by installing it with yarn.
  2. if expose must be used, they changed the API so new code should be something like:
environment.loaders.append('expose', {
  test: require.resolve('jquery'),
  loader: 'expose-loader',
  options: {
    exposes: ['$', 'jQuery'],
  },
});

Regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment