I've looked around for as much help as possible regarding installing jQuery in Rails 7 (7.0.2.3). I want to use it in script tags in my views, but I can't seem to get it exported to where it is globally available, er...ANYWHERE for that matter.
Sure importmaps is easy to manipulate as far as installing and mapping packages. Bravo. After that the whole documentation falls apart and a general haze clouds this new way of using js packages. Look around, there is plenty of confusion.
That said, how can I add this or something similar:
import jquery from "jquery"
window.jQuery = jquery;
window.$ = jquery;
to application.js or wherever to get a those global functions to work, like $. I'd like $ to be available in all my views.
As for what I've done:
./bin/importmap pin jquery --download
Gives me the importmap line:
pin "jquery" # @3.6.0
Ok. Then looking at the importmap JSON:
{
"imports": {
"application": "/assets/application-37a24e4747cc3cde854cbbd628efbdf8f909f7b031a9ec5d22c5052b06207eb8.js",
"@hotwired/turbo-rails": "/assets/turbo.min-96cbf52c71021ba210235aaeec4720012d2c1df7d2dab3770cfa49eea3bb09da.js",
"@hotwired/stimulus": "/assets/stimulus.min-900648768bd96f3faeba359cf33c1bd01ca424ca4d2d05f36a5d8345112ae93c.js",
"@hotwired/stimulus-loading": "/assets/stimulus-loading-1fc59770fb1654500044afd3f5f6d7d00800e5be36746d55b94a2963a7a228aa.js",
"jquery": "/assets/jquery-498b35766beec7b412bab57a5acbe41761daa65aa7090857db4e973fa88a5623.js",
"controllers/application": "/assets/controllers/application-368d98631bccbf2349e0d4f8269afb3fe9625118341966de054759d96ea86c7e.js",
"controllers/hello_controller": "/assets/controllers/hello_controller-549135e8e7c683a538c3d6d517339ba470fcfb79d62f738a0a089ba41851a554.js",
"controllers": "/assets/controllers/index-7a8fc081f7e391bd7b6fba95a75e36f88ba813da2c4c8787adad248afb9a0a06.js"
}
}
Ding. Appears it is there. Then a simple script tag in application.html.erb:
<script type="text/javascript" charset="utf-8">
$(document).ready(function (){
console.log('jQuery working.');
})
</script>
Fail. Inspector says:
(index):41 Uncaught ReferenceError: $ is not defined
This really seems so very basic and is thoroughly irritating not to have documentation on some of the most used libraries with importmaps like jQuery and Bootstrap.
This is day 1 stuff, and yet docs are so very sparse on these things. Seems like there should be some coordinated effort to really explain a change away from webpack which in and of itself was another fiasco.
Please, if you know the answer to this, post it so that everyone can benefit.
Thanks.