Search code examples
ruby-on-railsrubyimport-maps

Rails 7 - javascript importmap tags - custom for logged and nologged users


I think how to add custom application.js file for logged and nologged users i Rails 7 app with javascript_importmap_tags

It would be nice if there was an option to put the file name in the tag

<% javascript_importmap_tags 'filename' %>

but it is impossible. So how to attach another application.js file for users logged in Rails 7 with device gem ( application.html.erb and home.html.erb for logged user )


Solution

  • This will replace application.js with the "name" of your pinned file:

    <%= javascript_importmap_tags "name" %>
    

    To load another file in addition to application.js:

    <% if current_user %>
      <%= javascript_import_module_tag "account" %>
    <% end %>
    

    To do this from a template:

    # app/views/home/index.html.erb
    <% content_for :head do %>
      <%= javascript_import_module_tag "account" %>
    <% end %>
    
    # app/layouts/application.html.erb
    <head>
      # ...
      <%= yield :head %>
    </head>
    

    Update

    Any logic you want to apply here, you can just split javascript_importmap_tags:

    <%= javascript_inline_importmap_tag %>
    <%= javascript_importmap_module_preload_tags %>
    <%= javascript_importmap_shim_nonce_configuration_tag %>
    <%= javascript_importmap_shim_tag %>
    <%= javascript_import_module_tag "application" %>