我正在使用Rails + Webpack将bundle.js文件编译到Rails资产管道中。我在/ app / assets / images中放置了一个名为“ main.png”的图像。如何在捆绑的React组件中访问此图像?
我正在使用shakacode在rails gem上的反应。https://github.com/shakacode/react_on_rails
然后,我尝试使用webpack处理成功完成的图像,并将该图像放置在bundle.js文件旁边。我仍然在图像上看到404。
我知道我已经接近了,只是将rails资产设置为publicPath错误。当前设置提供了一个不兼容rails的localhost:3000 / webpack / main.png。
这是我的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
}
正确定义加载程序后require
,例如,您可以使用函数加载映像!例如,在您的进口附近添加:
const myImg = require('./assets/methods.png');
然后,在组件的render方法中:
<img src={myImg} />
那应该工作...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句