我无法使用 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/