ElMassimo / vite_ruby

⚡️ Vite.js in Ruby, bringing joy to your JavaScript experience
https://vite-ruby.netlify.app
MIT License
1.33k stars 122 forks source link

Support asset_host as a Proc #202

Closed lewisf closed 2 years ago

lewisf commented 2 years ago

Rails allows passing in a proc for asset host -- something like this:

ActionController::Base.asset_host = Proc.new { |source|
  "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com"
}

Passing in a Proc here currently breaks the helper template tags since the Proc case is not covered

ElMassimo commented 2 years ago

Hi Lewis! Thanks for reporting.

Usually, the asset host will be used as the base for Vite.

Since dynamic values for asset_host rely on the context of the source, there's no way to pass that to Vite.

A reasonable behavior when asset_host is a Proc would be not to expose it to vite-plugin-ruby, so that it uses / as the base.

You can try this fix by pinning vite_rails to the fix/asset-host-proc branch in this repo.


In order to better inform my decisions, what is your use case for a dynamic asset_host?

lewisf commented 2 years ago

Hey @ElMassimo -- I'll give this a look

We use ActiveAdmin, which serves it's own JS/CSS from the Rails web server. In order to ensure that that works, we've done something like:

    config.asset_host = proc { |source|
      if source.start_with?('/assets/active_admin')
        'localhost:3000'
      else
        'localhost:3036'
      end
    }

I'm not sure if there's a better way to do this, but open to suggestions

ElMassimo commented 2 years ago

Gotcha, since for development asset_host is typically not relevant, I think the fix I proposed should work for your use case as well.

What happens when you don't configure asset_host? Normally you wouldn't need to explicitly target the Vite dev server, as the proxy will redirect requests as needed.

I tried by adding activeadmin to the example app, and both Vite assets and ActiveAdmin assets are served as expected.

ElMassimo commented 2 years ago

Fixed in vite_ruby-3.1.1 and vite_rails-3.0.8, you can upgrade both by running bin/vite upgrade.