我使用rails + webpack将一个bundle.js文件编译到rails资产管道中。我在/app/assets/images中放置了一个名为"main.png“的图像。如何在捆绑的React组件中访问此图像?
我正在使用shakacode的react on rails gem。https://github.com/shakacode/react_on_rails
然后,我尝试使用webpack处理图像,它成功地处理了图像,并将图像放在bundle.js文件旁边。我在图像上还是得到了404。
我知道我已经很接近了,只是publicPath对于rails资产来说是错误的。这个当前的设置提供了一个本地主机:3000/webpack/main.png,它不能与rails一起工作。
这是我的webpack文件:
const webpack = require('webpack');
const path = require('path');
const devBuild = process.env.NODE_ENV !== 'production';
const nodeEnv = devBuild ? 'development' : 'production';
config = {
entry: [
'es5-shim/es5-shim',
'es5-shim/es5-sham',
'babel-polyfill',
'./app/Register.js',
],
output: {
filename: 'webpack-bundle.js',
path: '../app/assets/webpack',
publicPath: '/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: /\.jsx?$/, loader: 'babel-loader',
exclude: /node_modules/,
},
{
test: /\.(png|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&interlaced=false'
]
}
],
},
};
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
}
发布于 2016-09-10 13:01:30
正确定义加载器后,您可以使用require
函数加载您的图像,例如!例如,在您的导入附近添加:
const myImg = require('./assets/methods.png');
然后,在组件的render方法中:
<img src={myImg} />
应该行得通..。
https://stackoverflow.com/questions/39422223
复制相似问题