I just updated my Rails 6 app to Rails 7 and I am finding it difficult to hook my old "Vanilla Javascript" code into Rails' new setup with Turbo, Stimulus, and ImportMaps.
To make things easier, I simple ran rails new NewAppName
on the command line and then migrated my old legacy files bit by bit into the new application.
The ImportMap was generated for me by Rails. I only added the last line to include my old custom Javascript files.
config/importmap.rb:
# Pin npm packages by running ./bin/importmap pin "application", preload: true pin "@hotwired/turbo-rails", to: "turbo.min.js", preload: true pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true pin_all_from "app/javascript/controllers", under: "controllers" pin_all_from "app/javascript/components", under: "components" # these are the custom JS files from my old Rails 6 app
app/views/layouts/application.html.erb:
<head> ... <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> <%= javascript_importmap_tags %> <%= yield :head %><!-- load page specific custom JS here --> ... </head>
This is a typical JS file from my old app.
app/javascript/components/table_row.js:
function TableRow() { const rows = document.querySelectorAll('table tr[data-url]'); rows.forEach(row => { row.addEventListener('click', function(e) { handleClick(row, e); }); }); function handleClick(row, e) { const url = row.dataset.url; window.document.location = url; } } document.addEventListener('turbo:load', TableRow);
I replaced DOMContentLoaded
with turbo:load
in all my JS files to make it work with Turbo (hope that's correct?).
This is how I inject page-specific JS on certain pages:
app/views/quotes/index.html.erb
<% content_for(:head) do %> <%= javascript_import_module_tag "components/table_row" %> <% end %>
The problem now is that all this works somehow, however sometimes it doesn't and it's not very reliable. For example, the table_row.js
file should be loaded on index pages but sometimes it's not loaded and I don't really understand why.
I suspect that I mis-configured Turbo or Stimulus or my ImportMap somehow but don't really know where.
Can anybody tell me what I'm missing here?