shakacode / shakapacker

Use Webpack to manage app-like JavaScript modules in Rails
MIT License
430 stars 95 forks source link

append_javascript_pack_tag does not work inside a view component #495

Closed m0g closed 4 months ago

m0g commented 5 months ago

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:

tomdracz commented 5 months ago

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 https://github.com/shakacode/shakapacker/blob/dc921a20c75731ea4c23cecd4ff09cb7818ef002/lib/shakapacker/helper.rb#L209

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

justin808 commented 5 months ago

Is there a reason

  <%= javascript_pack_tag 'static' %>

is in the body and not the head?

justin808 commented 4 months ago

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