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?
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.
Most helpful comment
Let's say the pack is
app/javascript/packs/third-party.js.If assets have been compiled on your server:
If the assets live on another host, like a CDN:
There's no need for a
js.erbfile. You render the file contents as:textfrom your controller action:This example would assume you're not using the
splitChunksAPI, which would split your pack(s) up into multiple output files.