How to use JavaScript in Rails 7?

229 views Asked by At

I want to have a JavaScript file available for a view in my Rails app.

// app/javascript/custom/manage.js

document.body.style.backgroundColor = 'lightblue'
const test = document.getElementById('test')
# config/importmap.rb

pin_all_from "app/javascript/custom", under: "custom"
# app/views/locations/manage.html.erb

<%= javascript_include_tag "custom/manage", defer: true %>

When I navigate back to the manage view, I am getting the following error:

Uncaught SyntaxError: redeclaration of const test

I suspect this is because of how Turbo works. Because I tried commenting it out in the application.js file and the error was gone.

1

There are 1 answers

5
mechnicov On BEST ANSWER

As I understand, you need selective import modules feature

It's possible to selectively import modules on specific pages, add at the top of your view using content_for

<%# app/views/locations/manage.html.erb %>

<% content_for :custom_js do %>
  <%= javascript_import_module_tag "custom/manage" %>
<% end %>

And in the layout

<%= javascript_importmap_tags %>
<%= yield(:custom_js) %>

javascript_importmap_tags should be first