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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With