Rails 6 - How to include javascript_pack_tag in js.erb file

Viewed 2662

The pretty straightforward thing I would like to achieve. In js.erb file in my example new.js.erb I want to add my shared js

$('body').append('<%= j render partial: 'web/members/new_modal' %>');
$("#new-member-modal").modal();


<%= javascript_pack_tag 'src/remove_modal', 'data-turbolinks-track': 'reload' %>

File already exists in app/javascript/packs/src and compiles without errors.

 js/src/remove_modal-01129037158769dbdd16.js   689 KiB  src/remove_modal  [emitted] [immutable]  src/remove_modal
    js/src/remove_modal-01129037158769dbdd16.js.map   795 KiB  src/remove_modal  [emitted] [dev]        src/remove_modal

However, once the js.erb file is being fired I get an error in a browser console:

Uncaught SyntaxError: Unexpected token '<'
    at processResponse (rails-ujs.js:283)
    at rails-ujs.js:196
    at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.js:264)

Which refers to compiled javascript_pack_tag

<script src="/packs/js/src/remove_modal-22aa3c3bbe8f6a959aec.js" data-turbolinks-track="reload"></script>
3 Answers

I understood what I was doing wrong. First of all, I tried to generate an HTML script tag in .js.erb file what was just content type issue.

I was able to load the js file by doing

<%= render partial: 'web/members/remove_modal' %>

It's a step forward however still I would like to know how could I load a file from javascript/packs directory into js.erb

In my case, I needed to inject the pack tag on a website other than my own, so I ended up doing something like this.

var packScript = '<%= javascript_pack_tag("api_dashboard") %>';
var scriptSrc = packScript.split('"')[1];
scriptSrc = myHost + scriptSrc;
var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = scriptSrc;
    document.head.appendChild(script);

It's not the prettiest solution, but it worked for me.

Try this to add the element to the end of the body.

$('body').append('<%= j render partial: 'web/members/new_modal' %>');
$("#new-member-modal").modal();
$('body').append('<%= javascript_pack_tag 'src/remove_modal' %>');
Related