无法检索我的react组件中的图像

时间:2017-01-29 14:24:43

标签: image reactjs webpack urlloader

我对编码很陌生,所以请放纵......我搜索了很多,但我无法解决问题:(

我想通过和html img标签呈现我的图像。我看到最好的反应方式是导入我的图像。像这样:

import avatar from './avatar.png';

export default class Connection extends React.Component {
  render () {
      return (
        <div>
          {this.props.user.firstname}&nbsp;{this.props.user.lastname}
          &nbsp;<img src={avatar} className='img-circle' />
          &nbsp;&nbsp;&nbsp;<a href='#' onClick={this.props.logout}>Déconnexion</a>
        </div>
      );
  }
}

我使用以下webpack配置加载这些图像:

module: {
    loaders: [
      { test: /\.jsx?$/, exclude: [/node_modules/], loader: 'babel' },
      { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader?modules&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]!postcss-loader') },
      { test: /\.(png|gif|jpe?g|svg|jpg)$/i, loader: 'file-loader?hash=sha512&digest=hex&name=[path][name]-[hash].[ext]' },
      { test: /\.(png|gif|jpe?g|svg|jpg)$/i, loader: 'url-loader?limit=10000' }
    ]
  }

我看到webpack设法加载jpg或png文件但是当显示它时,似乎生成/复制的文件不可用(例如:/MyApp/avatar-50b93a2df8aec266d7c8c1c0f5719d1b.png不可用)。

我使用webpack dev服务器,因此我看不到捆绑的文件和dist或build文件夹。

有什么想法解决我的问题吗?

谢谢,

在img标签中使用require时,我收到以下错误:

找不到模块:错误:无法解析'file'或'directory'./ avatar

我试图在webpack配置中获取扩展名,但它没有解决任何问题:(

这是我的webpack配置中的公共路径配置:

output: {
    path: path.join(__dirname, '/build'),
    publicPath: '/',
    filename: 'bundle.js'
  }

2 个答案:

答案 0 :(得分:1)

要使用Webpack加载图像,您需要执行以下操作:

<img src={require('./avatar.jpg'})/>

Webpack遍历您的应用程序代码库,代码被捆绑到一个文件中,但是文件不会保存在同一个结构中,通过调用require Webpack将为您进行依赖管理,在这种情况下文件将移动并且代码将被注入,因此它指向它的捆绑位置。

答案 1 :(得分:0)

您可以从SurviveJS Book中查看这篇文章。 Load Images Chapter Extract from SurviveJS