Im trying to add som simple Ajax to my rails app. I am using Bootstrap with webpack.
My webpack/environment.js
file looks like this
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
My javascript/packs/application.js
looks like this
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
import 'bootstrap'
import 'src/main'
import 'style/main'
I'm trying to add some Ajax for one of my models in create.js.erb
$("#question-<%= @exam_option.exam_question.id %>-options").append("<%= escape_javascript render 'exam_option', option: @exam_option %>");
$('#add_option_modal').modal('hide');
When I try and add one of my options, I get the console error
ReferenceError: Can't find variable: $
I've searched for a solution and have been unsuccessful.
What am I doing wrong? Thank you!
Edit:
When I added Bootstrap to my app, I followed this guide . When following the guide, I installed bootstrap, jquery and popper.js with yarn
yarn add bootstrap jquery popper.js
The jQuery that Bootstrap uses is working correctly (such as tooltips).
as per @mechnicov's answer, I tried changing my environment.js
to
const webpack = require('webpack')
environment.plugins.append('Provide',
new webpack.ProvidePlugin({
$: 'jquery/src/jquery',
jQuery: 'jquery/src/jquery',
Popper: ['popper.js', 'default']
})
)
and I added require("jquery")
above import 'bootstrap'
in my application.js
when I made those changes, my code in create.js.erb
works correctly, but it makes my Bootstrap not function correctly and throw errors such as TypeError: ... $('[data-toggle="tooltip"]').tooltip() undefined
.
Edit 2
As per the accepted answer, I changed my application.js
to :
require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")
window.jQuery = window.$ = require('jquery')
import 'bootstrap'
import 'src/main'
import 'style/main'
All seems to be working correctly, but I'm unsure why I need to add it this way? isn't Webpack supposed to do this from my environment.js
file?
If someone can explain this, please do.
Can you try below code :-
# javascript/packs/application.js
window.jQuery = window.$ = require('jquery')
OR
# javascript/packs/application.js
require("jquery")
window.jQuery = $;
window.$ = $;
I was also facing same problem but above code was worked for me at that time
Hope this will help you also. :)
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