Should I be using the Gemfile javascript library when using yarn with Rails 5.1?
I am trying to get some jQuery stuff in Rails 5.1. Since jQuery support is dropped (by default), I am having a hard time finding the exact workflow I should be using.
I would try some Ajax stuff first, but then I realized that the "$" is not defined in the web developer console. This confirms that jQuery is indeed not installed by default.
1 .. The first thing I did was just put the jQuery cdn script hard-coded in the app layout view, something like this in app/views/layouts/application.html.erb
:
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
It worked. But I think this is not a supported way to do it.
2. Then I tried to install jquery using yarn, since I have a Rails 5.1 setup with thread already installed.
- I ran
yarn add jquery
, thenyarn
(it seems the latter is unnecessary) - I added
//= require jquery
to the fileapp/assets/javascripts/application.js
It worked too.
Edit: I just noticed there is a command rails yarn:install
, should I use it instead of the native native narn command?
But then I wanted to play with some jQuery-ui products. Noticing that the package jquery-ui
exists in the yarn, I did the same:
- I run
yarn add jquery-ui
thenyarn
again - I added
//= require jquery-ui
to the fileapp/assets/javascripts/application.js
right underjquery
one
But it didn't work. Then I noticed that some people link to jquery gems, especially gems jquery-rails
and jquery-ui-rails
.
My question is, despite having a working thread, should I be using linked gems?
In my case, should I use both of these stones? Or should I install just jquery-ui-rails
from the moment jquery is installed using yarn?
Sorry, but this asset management thing hasn't gotten into my head yet. And no web packaging products launched yet đ
source to share
I did it working without Rails gems and with yarn bundles.
Instead of this
Gemfile:
gem 'jquery-rails'
gem 'jquery-ui-rails'
Decision.
add yarn packages to package.json
{
...
"dependencies": {
"jquery": "3.2.1",
"jquery-ui-dist": "1.12.1",
"jquery-ujs": "1.2.2",
.. more packages here
}
}
Attention! it uses jquery-ui-dist package (not jquery-ui).
application.js:
//= require jquery/dist/jquery
//= require jquery-ujs
//= require jquery-ui-dist/jquery-ui
About jquery-ui packages: The jQuery-ui package on NPM is not prebuilt and therefore does not contain jquery-ui.js; the package will either be built before use or all widgets included / used separately. More details in this discussion - jquery-ui and webpack, how to manage it in a module? ...
source to share