Search code examples
ruby-on-railswebpacker

packs url equivalent for asset_url?


I'm upgrading a Rails 5 app to Rails 6, so in Rails 5 before webpacker was the default, I had a js file that I was loading separately from the application.js like this:

In config/initializers/assets.rb

Rails.application.config.assets.precompile += %w(magic.js)

and in my views I was using it like this:

<%= asset_url('magic.js'); %>

Now as Rails 6 uses webpack, I am adding the magic.js file to app/javascript/packs (which makes it as an entry file) and will produce a separate magic.js output in plus of the application.js, however I can't find any helper to access the URL, i.e: packs_url (equivalent to asset_url)

Does anyone have an idea?


Solution

  • You are currently using webpacker. So, You can use javascript_pack_tag to render javascript pack files.

    Here is an example:

    <%= javascript_pack_tag 'magic' %>
    

    For getting the url:

    <%= asset_pack_path 'magic.js' %>
    

    For more information visit docs:

    https://github.com/rails/webpacker#usage

    https://www.rubydoc.info/github/rails/webpacker/Webpacker%2FHelper:asset_pack_path