2017-04-06 92 views
3

我在使用Webpack和React的简单应用程序中显示简单图像时遇到了问题。在使用Webpack的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
    • 图像0​​
      • PIVX_Pla net_1a_239x83.png
    • index.html的 ...

任何见解?

回答

2

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

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

因为图像是app目录下,而不是components下从正在试图获得image位置

也使确定你所有的loaders安装正确

+0

奏效!谢谢。不知道错过了什么(我曾尝试过)。我也必须安装:npm install url-loader –

+0

我试过了。系统说我需要15+声望才能这样做(我现在只有10个)。 –

+0

或者我明白了。是的,我接受它作为答案。 –

0

你也可以试试让:

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

始终使用让尽可能避免范围怪物