Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure Bootstrap plugins with Rails + Webpack?

I'm setting up a new rails project with webpack, but I can't figure it out how to enable Bootstrap plugins (tooltip, alert, etc).

1) Installed dependencies:

yarn add bootstrap jquery popper.js

2) I've required the modules in app/javascript/packs/application.js:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
require("jquery")
require("popper.js")
require("bootstrap")

3) Enabled $ y jQuery in the global scope:

const webpack = require('webpack')
environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery/src/jquery',
    jQuery: 'jquery/src/jquery'
  })
)

4) In my views:

<button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="top" title="Tooltip">
  Button
</button>

I know JQuery is working, because I can run something like $('#some-id') from browser console. But I can't use Bootstrap's plugins. The button doesn't show the tooltip.

If I type $('#some-id').tooltip() or $('#other-id').alert() I get the following error:

Uncaught TypeError: $.alert is not a function

How can I fix this? I've read that I need to importo plugins individually, but it's not working for me:

import 'bootstrap/js/dist/alert';

Is there something that I'm missing?

like image 738
wacko Avatar asked Nov 06 '22 11:11

wacko


1 Answers

Try this

Rails 6.0.1

config/webpack/enviornment.js

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

environment.plugins.prepend('Provide',
  new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
  })
)

module.exports = environment

app/javascript/packs/application.js

import "../stylesheets/application"

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

import 'bootstrap/js/src/tooltip'
import 'bootstrap/js/src/alert'

import './main'

window.$ = window.jQuery = $ // make $ available in console for debugging

app/javascript/packs/main.js

// Wait for turbolinks load event
$(document).on('turbolinks:load', () => {
  $('[data-toggle="tooltip"]').tooltip()
  $('.alert').alert()
})

app/javascript/stylesheets/application.scss

$primary: #757575;
$light: #e9ecef;

@import 'bootstrap';
@import 'custom.css';

to load above stylesheets

layouts/application.html.erb.

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

or replace stylesheet_link_tag with stylesheet_pack_tag. if you don't want to use stylesheets in assets/stylesheets

like image 124
PGill Avatar answered Nov 12 '22 13:11

PGill