I am working on an application with Rails 6 / Webpack that uses different subdomains, and for each subdomain we associate different users, stylesheets, etc. I would like to import conditionally my project images depending on the domain. Currently, my app/javascript/pack/application.js do this for importing common images
require.context('../images',true)
However, if I create a separate folder for the images (let's say images_subdomainfoo)
and I attempt some conditional import like
const foo = import("images_subdomainfoo/bar.png")
this image is compiled even when the file containing the statement is not imported (for example, I placed that line in a subdomainfoo.js file and then added this line in my HTML header file
<%= javascript_pack_tag 'subdomainfoo', 'data-turbolinks-track': 'reload' if request.subdomain == "foo" %>
but the image is loaded regardless the subdomain).
I've seen some approachs like the NormalModuleReplacementPlugin but I am not sure how to incorporate that into a Rails 6 application, since it involves starting webpacker with special options like npx webpack --env APP_TARGET=VERSION_A
Any suggestion would be appreciated.
You could add the following line to your _head.html.erb (above javascript_pack_tag):
<script>
window.subdomain = '<%= request.subdomain %>'
</script>
This would ensure that your subdomain-name is attached to the Global Object which is accessible in Javascript.
Then you can add the following line to your app/javascript/pack/application.js - assuming your images are placed inside folders named after your subdomains.
const foo = import(`images_${window.subdomain}/bar.png`)