Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
Conditional image import with Webpack in Rails 6

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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`)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!