Webpacker: Question: How can I render a webpack js file from my rails controller?

Created on 5 Aug 2020  路  2Comments  路  Source: rails/webpacker

My situation is similar to the one here: https://github.com/rails/webpacker/issues/334

I hand off a script to a client that points to my Rails Controller, which renders a .js.erb file. I would like to load a React application from this file, and attach it to a DOM element on my clients website. That seems to have been discussed briefly in the issue I posted above.

I'm thinking it would also work to just have my Rails Controller link to the javascript/packs file directly. Is there a way I can render a javascript file in the javascript/packs folder from my Rails Controller? Or is there a way I can render webpack output in a .js.erb file?

Most helpful comment

Let's say the pack is app/javascript/packs/third-party.js.

If assets have been compiled on your server:

file_contents = File.read(File.join(Rails.public_path, asset_pack_path('third-party.js')))

If the assets live on another host, like a CDN:

file_contents = URI.open(asset_pack_url('third-party.js')).read

There's no need for a js.erb file. You render the file contents as :text from your controller action:

respond_to do |format|
  format.js { render text: file_contents }
end

This example would assume you're not using the splitChunks API, which would split your pack(s) up into multiple output files.

All 2 comments

I'm using this approach now, but I came here to ask the same question. Would prefer a render of pack contents instead of redirect.
https://www.mikewilson.dev/posts/redirecting-to-static-webpacker-content-with-rails/

Let's say the pack is app/javascript/packs/third-party.js.

If assets have been compiled on your server:

file_contents = File.read(File.join(Rails.public_path, asset_pack_path('third-party.js')))

If the assets live on another host, like a CDN:

file_contents = URI.open(asset_pack_url('third-party.js')).read

There's no need for a js.erb file. You render the file contents as :text from your controller action:

respond_to do |format|
  format.js { render text: file_contents }
end

This example would assume you're not using the splitChunks API, which would split your pack(s) up into multiple output files.

Was this page helpful?
0 / 5 - 0 ratings