我正在使用rails webpack将bundle.js文件编译到rails资产管道中 . 我在/ app / assets / images中放置了一个名为“main.png”的图像 . 如何在捆绑的React组件中访问此图像?
我'm using shakacode'对rails gem做出反应 . https://github.com/shakacode/react_on_rails
然后我尝试使用webpack处理它成功完成的图像,并将图像放在bundle.js文件旁边 . 我仍然在图像上得到404 .
我知道我很接近,只是将railsPath错误地用于rails资产 . 这个当前设置提供了localhost: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
}
1 回答
正确定义加载程序后,您可以使用
require
函数加载图像!例如,在您的导入附近添加:const myImg = require('./assets/methods.png');
然后,在组件的render方法中:
<img src={myImg} />
这应该工作......