我正在使用Rails 5.1和Webpacker。一切正常。我正在使用/ app / javascripts / images中的反应组件中的图像,我将它们很好地导入到我的组件中,并且一切都在开发中。
然而 - 当我部署时,内部图像现在直接从我的网站url提供(使用他们的webpacker编译路径,但问题是我已经设置了我的生产环境以使用asset_host - 所以Rails正确地为我的所有其他常用的Rails图像资源(包括我的反应JS包) - 所以它们都是从我的asset_host正确提供的。
我导入到我的反应组件中的/ app / javascripts / images中的内部图像 - 它们不是通过asset_host代理的。 (它在开发中工作正常 - 因为我没有在那里使用asset_host。)
我怎样才能让webpacker知道我需要在生产时通过asset_host代理的图像?
答案 0 :(得分:0)
我设置了我的config/webpack/environment.js
文件,如下所示:
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
根据以下评论:https://github.com/rails/webpacker/issues/1186#issuecomment-358110765
答案 1 :(得分:0)
您可以将环境参数“ process.env.WEBPACKER_ASSET_HOST
”添加到/config/webpack/production.js
文件中。
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()
我在rails6中工作。希望这可以帮助某人