【问题标题】:Module parse fails for .jpg in <img> for React component?React 组件的 <img> 中的 .jpg 模块解析失败?
【发布时间】:2017-12-30 17:50:34
【问题描述】:

我想在我正在使用 react 构建的网站上显示一张图片。下面是组件源代码:

import React, { Component } from 'react';
import style from './styles/AboutMeStyle.css';

export default class AboutMe extends Component{
    render(){
        return (
            <div>
                <img src={require ('./images/ProfilePic.jpg')}align="middle"/>
            </div>
        );
    }
}

该文件似乎已找到,但我不断收到异常,指出模块解析失败...?这是来自终端的错误文本输出:

Module parse failed: /Users/megan/Desktop/Personal Website/client/components/images/ProfilePic.jpg
Unexpected character (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character (1:0)
...

我是不是写错了代码?还是我缺少一个模块?我已经安装了 image-webpack-loader 但它似乎没有做任何事情......这是我的 webpack.config.js :

module.exports = {
    entry: './client/index.js',
    output: {
        path: __dirname + '/public/js',
        filename: 'bundle.js'
    },
    devtool: 'source-map',
    stats: {
        colors: true,
        reasons: true
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules)/,
                loaders: ['babel']
            },
            {
                test: /\.css$/,
                loaders: ['style-loader', 'css-loader']
            }
        ]
    }
}

【问题讨论】:

  • 请将图片替换为实际的错误信息。这将有助于使这个问题更易于搜索。
  • 完成。将图片替换为文字

标签: javascript html node.js reactjs webpack


【解决方案1】:

require 用于导入javascript代码。你可能想要这样的东西:

<img src="/images/ProfilePic.jpg" align="middle"/>

将从您的公共图像文件夹中读取。更仔细地查看您的终端,我发现您的图像位于 components 文件夹中。通常,除了 javascript 组件之外,您还希望在公共目录中拥有一些图像/其他资产文件夹。

Webpack 会将所有代码编译成一个包,您的网络服务器将公开根目录下的公共文件。

请参阅webpack publicPath config options 了解更多信息。

【讨论】:

  • 谢谢!将图像移动到 /public/images 文件夹成功!
猜你喜欢
  • 2016-05-30
  • 2022-01-26
  • 2017-06-01
  • 2021-05-01
  • 2019-05-20
  • 1970-01-01
  • 2021-03-15
  • 2019-07-17
  • 1970-01-01
相关资源
最近更新 更多