Webpack静态图片无法加载

4

我正在使用Webpack开发React项目,但在静态图片加载方面遇到了问题。虽然loader似乎已经将图片正确转换为URL,但在页面呈现时img的src却无法正常工作。图片的相对路径是正确的。以下是我的代码:

webpack.config.dev.js:

module: {
loaders: [
  {
    test: /\.css$/,
    exclude: /node_modules/,
    loader: 'style-loader!css-loader?localIdentName=[name]__[local]__[hash:base64:5]&modules&importLoaders=1&sourceMap!postcss-loader',
  }, {
    test: /\.css$/,
    include: /node_modules/,
    loaders: ['style-loader', 'css-loader'],
  }, {
    test: /\.jsx*$/,
    exclude: [/node_modules/, /.+\.config.js/],
    loader: 'babel',
  }, {
    test: /\.(jpe?g|gif|png|svg)$/i,
    loader: 'url-loader',
    options: {
      limit: 25000,
    },
  }, {
    test: /\.json$/,
    loader: 'json-loader',
  }, { 
    test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' }
],
},

React代码

import React, { Component} from 'react';

import styles from './Album.css';

const logo = require('./img/MoP.png');

export class Album extends Component{
  constructor(props){
    super(props);

    console.log(logo);
}

render(){
    return (
        <div className = {styles.album}>
            <div className="row">
                <div className="col-8">
                    <div className="albumInfo">
                        <h6> {this.props.title} </h6>
                        <h6> {this.props.artist} </h6>
                        <h6> {this.props.date} </h6>
                        <h6> Rating: {this.props.rating} </h6>
                        <h6> {this.props.comment} </h6>
                    </div>
                </div>
                <div className="col-4 align-self-center">
                    <img src={logo}></img>
                </div>
            </div>
        </div>
    )
}
}

export default Album;

我尝试了使用url-loader和file-loader的不同方法,但是到目前为止都没有成功。希望能得到一些帮助!谢谢。

console.log(logo) 的输出结果为:data:image/png;base64,bW9kdWxlLmV4cG9ydHMgPSBfX3dlYnBhY2tfcHVibGljX3BhdGhfXyArICJhNDVlZjc0ZTc5MjY3ZDZkNzcxMWFjYmI2ZDA1ZGU4Zi5wbmciOw== - Clay Schnars
请尝试将logo值用引号括起来,并使img标签成为自闭合的。如下所示:<img src="{logo}"/>,不需要 </img> - DSCH
“不起作用”是什么意思?是指图片损坏、完全没有图片等吗?您能否使用浏览器的开发工具检查DOM并查看src图像?这可能只是CSS问题。 - Andrea Carraro
@toomuchdesign 问题在于没有任何图像显示出来。检查元素后,base64编码字符串出现在img src中,但图像未被渲染。 - Clay Schnars
@DSCH 我尝试了你的建议,但是出现了404错误,如下所示:GET http://localhost:8000/%7Blogo%7D 404 (未找到) - Clay Schnars
2个回答

7
看起来从webpack配置文件来看,你两次使用了相同的url-loader处理同一种文件类型。这可能会破坏你的图像输出。

2
我的程序出现了问题,因为我同时对同一文件运行了file-loader和url-loader。 - rgdigi

1
你看到的是图像的base64编码。 我不熟悉 'url-loader',但快速查看他们的页面表明它将图像加载为base64。 您可以在此处找到有关其的一些有用信息:https://css-tricks.com/data-uris/ 如果您更喜欢图像路径而不是base64,请考虑使用其他加载程序。希望能帮到您。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接