javascript - React 组件的 <img> 中的 .jpg 模块解析失败?

标签 javascript html node.js reactjs webpack

我想在我使用 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']
            }
        ]
    }
}

最佳答案

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

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

将从您的公共(public)图像文件夹中读取。仔细观察您的终端,我发现您的图像位于 components 文件夹中。通常,除了 javascript 组件之外,您还希望在公共(public)目录中放置一些图像/其他 Assets 文件夹。

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

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

关于javascript - React 组件的 <img> 中的 .jpg 模块解析失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45292515/

相关文章:

node.js - 一个更简单的 node.js Markdown 转换器

PHP 数组转换为 javascript 数组

html - 如何从 html 表格的最后一行中删除底部边框?

javascript - 简单js函数调用引用错误

arrays - 无法将 EJS 变量插入 html scripttag 中的数组?

javascript - 如何在保护 api key 的同时使用 javascript api?

javascript - 如何测试具有关系依赖性的 Ember 模型的计算属性?

Javascript动态方法调用

javascript - Github 页面网站不反射(reflect)本地主机的行为

javascript - 如何将菜单和菜单项角色的默认 JAWS 读取更改为自定义角色?