Search code examples
ruby-on-railswebpackbootstrap-4webpacker

Error while using Bootstrap 4 with Rails 6 Webpacker


I have a very simple Rails 6 application with jquery configured as follows:

config/webpack/environment.js :

const { environment } = require('@rails/webpacker');

const webpack = require('webpack');

environment.plugins.append('Provide', new webpack.ProvidePlugin({
    $: 'jquery/dist/jquery.min',
    jQuery: 'jquery/dist/jquery.min',
    Popper: ['popper.js', 'default']
}));

module.exports = environment;

I am trying to use Bootstrap. However, I am not able to use any Bootstrap JS method with JQuery selector.

Example:

$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});

// Error: Uncaught TypeError: $(…).tooltip is not a function

Any help would be highly appreciated! Thanks


Solution

config/webpack/environment.js :

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;

Solution

  • (1)

    You're using turbolinks, so instead document:ready you should rely on turbolinks:load event

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

    (2)

    Don't use minified javascript libraries

    // application.js
    import "bootstrap"
    
    // config/webpack/environment.js
    environment.plugins.append('Provide', new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery',
      Popper: ['popper.js', 'default']
    }));