shakacode/shakapacker

append_javascript_pack_tag does not work inside a view component

Closed this issue · 3 comments

m0g commented

Notice: A bug is a crash or incorrect behavior. If you have a debugging or troubleshooting question, please open a discussion on the Discussions Tab. Otherwise, remove this line and fill out the following sections.

Hello there,
I'm having an issue regarding shakapacker and view_components. I'm filling a bug report here, because I assume the issue is on shakapacker's side. Please correct me if I'm wrong.

The problem I am experiencing, is that it is currently not possible to append javascript pack tag from within a view component.

Expected behavior:

Hello should be displayed in the console

Actual behavior:

Hello is not displayed in the console

Small, reproducible repo:

app/views/layouts/application.html.erb

<html>
  <body>
    <%= render(FooterComponent.new) %>
    <%= javascript_pack_tag 'static' %>
  </body>
</html>

app/components/footer_component.html.erb

<% append_javascript_pack_tag 'cookie_banner' %>
<% append_stylesheet_pack_tag 'cookie_banner' %>
<footer class="border-t border-me-gray-400 py-8 bg-me-gray-100">
  my footer
</footer>

app/components/footer_component.rb

class FooterComponent < ViewComponent::Base
end

app/javascript/packs/cookie_banner.js

console.log('hello');

Setup environment:

  • Ruby version: 3.2.4 (2024-04-23 revision af471c0e01) [arm64-darwin23]
  • Rails version: 7.1.3.4
  • Shakapacker version: 8.0.0

Had a look at this and I think this is something to do with rendering contexts.

We rely on instance variables being available on instance of ActionView IIRC

@javascript_pack_tag_queue ||= {

Testing this out and prying in the view and footer component I can see that while both have access to javascript_pack_tag_queue for example, the one in view component is a different instance so it stores state local to that component.

This is different to plain rendering view or partial where same ActionView base will be reused so the state is global.

Not too familiar with view components rendering but can't see an easy way we could fix it on our end

Is there a reason

  <%= javascript_pack_tag 'static' %>

is in the body and not the head?

Closing for now. Seems to be either a doc issue or a patch is needed for view compnents.