image - 使用 Webpack 在 React 中加载图像

标签 image reactjs webpack png

我无法使用 Webpack 和 React 在简单的应用程序中显示简单的图像。

我已经阅读了这篇文章并尝试了几种不同的方法,但不断收到各种错误,或者最多有时没有错误,但也没有图像显示。

这是我的 React 组件:

import React from 'react';
import styles from '../css/main.css';

import Menu from './Menu';

const logo = require('./images/PIVX_Planet_1a_239x83.png');

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {test: 'foo'};
  }
  render() {
    return (
      <div>
        <div id='container'></div>

        <div className={styles.logo}>
          <img src={logo}/>
        </div>
        <div>
          <Menu/>
        </div>
      </div>
    );
  }
}

这是我的 webpack 配置:

...
module: {
    loaders: [{
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        "presets": ["react", "es2015", "stage-0", "react-hmre"]
      }
    }, {
      test: /\.(jpg|png|svg)$/,
      loader: 'url-loader',
      options: {
        limit: 25000,
      },
    }, {
      test: /\.json?$/,
      loader: 'json'
    }, {
      test: /\.css$/,
      loader: 'style!css?modules&localIdentName=[name]---[local]---[hash:base64:5]'
    }]
  }
...

这样,在控制台中从 webpack 中获取错误:

ERROR in ./app/components/App.js Module not found: Error: Cannot resolve 'file' or 'directory' ./images/PIVX_Planet_1a_239x83.png in /Users/mac/_DEV/_LAB/PIVX/PIVX-Planet-2/app/components @ ./app/components/App.js 67:11-56

我也尝试过使用 babel-plugin-transform-react-jsx-img-import (https://www.npmjs.com/package/babel-plugin-transform-react-jsx-img-import)

然后只需使用:

<div className={styles.logo}>
  <img src="./images/PIVX_Planet_1a_239x83.png"/>
</div>

在这种情况下,没有错误,但图像显示为损坏。

我尝试使用所有这些组合更改图像的相对路径。

目录结构:

  • 应用程序
    • 组件
      • App.js
    • 图像
      • PIVX_Planet_1a_239x83.png
    • index.html ...

有什么见解吗?

最佳答案

根据您的目录结构,您需要使用的路径是

const logo = require('../images/PIVX_Planet_1a_239x83.png');

因为图像位于 app 目录下,而不是在您尝试获取image 位置的 components

还要确保所有加载器均已正确安装

关于image - 使用 Webpack 在 React 中加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43246372/

相关文章:

image - 使用不同尺寸但相同数量的 HoG 特征的图像训练分类器

reactjs - 将箭头功能更改为组件列表

reactjs - 来自库的 React 上下文未在消费者中更新

javascript - 当api通过reducer来自某个状态时,如何使用axios获取?

reactjs - 无法使用 "babel-plugin-react-css-modules"导入 CSS - 获取 "ParseError: Unexpected token"

javascript - webpack、rollup 等模块打包器如何处理相同依赖项的两个不同版本?

javascript - 我如何为 webpack 创建一个通过函数公开所有源的加载器?

CSS Sprites 在图像上显示损坏的图像图标,但悬停仍然有效

c# - 在 Windows 10 中配置图像控件

c++ - 使用二进制确定图像文件的扩展类型