I'm currently trying Rails 6.0.0 which seems to have moved the default javascript
folder from app/assets/javascript
to app/javascript
. The application.js
file is now located in app/javascript/packs
.
Now, I want to add JS file for each controller action. For example I have:
UsersController#index
UsersController#show
UsersController#edit
On some controller action I need to add some javascript:
app/javascript/user/index.js
app/javascript/user/show.js
app/javascript/user/edit.js
app/javascript/user/form.js
(assume in form I need some js tweak)
Here is what I'm currently doing. In controller view:
<%= javascript_pack_tag 'user/index', 'data-turbolinks-track': 'reload' %>
However, in index.js
I can't call libraries which has been required in application.js
. For example in application.js:
require("bootstrap/dist/js/bootstrap")
In index.js I call bootstrap specific JS for popover, modal ... I got:
Uncaught TypeError: $(...).modal is not a function
I don't want to write all JS in application.js because every page have to load entire website JS which is nut! That why I want to split them and include when I need.
Beside, why we have to require JS file in application.js
? If we using javascript_pack_tag
do we need to require those file in application.js
?
Here is a dummy repo I just created.
Ref: here explain how to require a custom JS file.