我想在我使用 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/