How to use jQuery & jQueryUI with Esbuild Discussion
If we're not using jQueryUI or any library that depends on jQuery, then are these lines enough by themselves?
window.jQuery = jquery;
window.$ = jquery;
Should do. You have to make sure to import jquery first after the yarn install
import jquery from 'jquery';
window.jQuery = jquery;
window.$ = jquery;
I have done all of the above. But, jquery is not available in my html.erb files inside the tag.<br> e.g. say inside app/views/home/index.html.erb</p> <script> $( () => { console.log("Hello World!"); });
I get the error:
Uncaught ReferenceError: $ is not defined
Two things to check.
1) If you're sprinkling snippets of jQuery in your views, you'll want to look at application.html.erb and make sure the javascript_include_tag does not have "defer: true". So just:
javascript_include_tag "application", "data-turbo-track": "reload"
2) If you are using jQuery in your Stimulus controllers, make sure to import the jQuery before you import the controllers. I had to do:
import "./src/jquery"
import "./controllers"
Thanks.
This did not work, instead produced runtime error.
I will be using jquery within stimulus controller instead, which worked for me.
Also, there are errors like: ActionController::RoutingError (No route matches [GET] "/images/ui-icons_555555_256x240.png")
I have copied these icons from the downloaded jquery-ui-1.13.0.custom zip file into the app/assets/images folder and inside app/assets/config/manifests added //= link_tree ../images
I really admire this episode, I cannot imagine how much effort did you put to find these solution to import jQuery and jQuery UI in to Rails. But since when it's become this complicated just trying to import jQuery in our web application? :'(
I'm trying to use the same approach for select2, but doesn't work for me, I have this error in the browser console.
admin-2ddc00f8a5f543e218a75bb46242ae32f3232f28f249c68cd24f4017022e3cbb.js:19594
Uncaught TypeError: $(...).select2 is not a function
For people coming from Rails 7, if you have already followed the video and installed jquery, $ is available in developer console; however, the view still raises "Uncaught ReferenceError: $ is not defined".
Try to load the jquery in separate file without "type: module"
= javascript_include_tag "application", "data-turbo-track": "reload", type: "module"
= javascript_include_tag "jquery", "data-turbo-track": "reload"