对于React组件,<img>中的.jpg模块parsing失败?

我想在我的网站上显示一个图像,我正在使用反应。 这里是组件源代码:

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> ); } } 

该文件似乎被发现,但我不断收到一个exception,说明模块parsing失败…? 这里是来自terminal的错误的文本输出:

 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"/> 

这将从您的公共图像文件夹读取。 更仔细地看你的terminal,我看到你的components文件夹里面有你的图片。 通常情况下,除了JavaScript组件之外,您还希望在公共目录中包含一些图像/其他资源文件夹。

Webpack会将所有代码编译成一个包,并且你的web服务器将公开文件暴露在根目录下。

请参阅webpack publicPath config选项以获取更多信息。