0

I am using Rails 5.1 and Webpacker. It all works fine. I am using images inside my react components that are in /app/javascripts/images, and I import them fine into my components and all is well on development.

However - when I deploy, the internal images are now served directly from my site url (with their webpacker compiled paths, but the problem is I have set up my production environment to use an asset_host - so Rails is correctly prefixing all my other usual Rails image assets (including my react JS packs) - so they are all being served correctly from my asset_host.

JUST the internal images that are in /app/javascripts/images that I imported into my react components - they AREN'T being proxied through the asset_host. (it works fine in development - as I don't use an asset_host there).

How can I let webpacker know, that I need the images proxied through an asset_host on production?

Joerg
  • 3,553
  • 4
  • 32
  • 41

2 Answers2

1

You can add an environment argument "process.env.WEBPACKER_ASSET_HOST" to /config/webpack/production.js file.

process.env.NODE_ENV = process.env.NODE_ENV || 'production'

process.env.WEBPACKER_ASSET_HOST = process.env.WEBPACKER_ASSET_HOST || '/yourpath/'

const environment = require('./environment')

module.exports = environment.toWebpackConfig()

i am working in rails6. hope this can help someone

Lorenzo
  • 11
  • 1
0

I managed top set up my config/webpack/environment.js file up like this:

const { environment } = require('@rails/webpacker')
const env = process.env.NODE_ENV || 'development'
const { resolve } = require('path')
const { safeLoad } = require('js-yaml')
const { readFileSync } = require('fs')
const filePath = resolve('config', 'webpacker.yml')
const appConfig = safeLoad(readFileSync(filePath), 'utf8')[env]
const config = appConfig

const removeOuterSlashes = string =>    
  string.replace(/^\/*/, '').replace(/\/*$/, '')

const formatPublicPath = (host = '', path = '') => {    
  let formattedHost = removeOuterSlashes(host)    
  if (formattedHost && !/^http/i.test(formattedHost)) {   
    formattedHost = `//${formattedHost}`    
  }   
  const formattedPath = removeOuterSlashes(path)    
  return `${formattedHost}/${formattedPath}/`   
}

const fileLoader = environment.loaders.get('file')
fileLoader.use[0].options.publicPath = formatPublicPath(process.env.WEBPACKER_ASSET_HOST, config.public_output_path)

module.exports = environment

According to the following comment here: https://github.com/rails/webpacker/issues/1186#issuecomment-358110765

Joerg
  • 3,553
  • 4
  • 32
  • 41