我正在使用 webpack 和 React on Rails,并且有一些需要引用图像的反应组件。
我遇到的问题是试图让 Rails 访问图像。Rails 从其通常的 app/assets/images 目录提供图像,该目录通过 url /assets 访问
但是,如果我在图像目录中有一个反应组件和一个图像:
组件.js
图片/image.jpg
+--component.js +--images/image.jpg
如果我尝试通过其在 component.js 中的相对路径来引用图像,例如当我在 rails 中加载页面时,页面会尝试访问 url http://localhost:3000/home/images/image.jpg而不是那个rails 期望资产为http://localhost:3000/assets/images/image.jpg
有谁知道如何纠正这个?
这是我的 webpack.config
const webpack = require('webpack')
const path = require('path')
const devBuild = process.env.NODE_ENV !== 'production'
const nodeEnv = devBuild ? 'development' : 'production'
const config = {
entry: [
'whatwg-fetch',
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill',
'./app/bundles/index.js'
],
output: {
filename: 'webpack-bundle.js',
path: '../app/assets/webpack'
},
resolve: {
extensions: ['', '.js', '.jsx'],
alias: {
react: path.resolve('./node_modules/react'),
'react-dom': path.resolve('./node_modules/react-dom')
}
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv)
}
})
],
module: {
loaders: [
{
test: require.resolve('react'),
loader: 'imports?shim=es5-shim/es5-shim&sham=es5-shim/es5-sham'
},
{
test: /\.(jpe?g|png|gif|svg|ico)$/, loader: 'file-loader'
},
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/
}
]
}
}
module.exports = config
if (devBuild) {
console.log('Webpack dev build for Rails') // eslint-disable-line no-console
module.exports.devtool = 'eval-source-map'
} else {
config.plugins.push(
new webpack.optimize.DedupePlugin()
)
console.log('Webpack production build for Rails') // eslint-disable-line no-console
}