我有一个矩形组件。我正在忙于在组件中渲染图像。我在尝试将徽标加载并呈现到组件中时遇到问题。我遇到解析失败,我不确定为什么会出现此错误:
Uncaught Error: Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)
at eval (splittlogo_logo_transparent.png:1)
at Object../client/dist/splittlogo_logo_transparent.png (bundle.js:96)
at __webpack_require__ (bundle.js:20)
at eval (topbar.jsx:13)
at Object../client/src/components/topbar/topbar.jsx (bundle.js:120)
at __webpack_require__ (bundle.js:20)
at eval (App.jsx:13)
at Object../client/src/components/App.jsx (bundle.js:108)
at __webpack_require__ (bundle.js:20)
at eval (index.jsx:9)
这是我的代码:
import React, { Component } from 'react';
import Logo from '../../../dist/splittlogo_logo_transparent.png'
export default class TopBar extends Component{
constructor(props){
super(props),
this.state = {
product:"",
}
}
userSearch(e){
console.log(e.target.value)
}
render(){
return(
<div className="topbar-coutainer">
<div className="logo-container">
<img src={Logo} alt=""/>
</div>
<div>
<input onChange={(e) => {this.userSearch(e)}} type="text" name="search" />
</div>
</div>
)
}
}
徽标的路径正确
这是我的网络包:
const path = require("path");
const webpack = require('webpack')
require("fs")
module.exports = {
mode: "development",
entry: path.resolve(__dirname, "./client/src/"),
output: {
path: path.resolve(__dirname, "./client/dist"),
filename: "bundle.js"
},
module: {
rules: [
{
loader: "babel-loader",
test: /.js[x]?/,
exclude: /node_modules/,
options: {
presets: ["react", "env"]
}
},
{
test: /.css$/,
use: [
{ loader: "style-loader" },
{
loader: "css-loader",
options: {
modules: true,
localIdentName: '[hash:base64]'
}
}
]
}
],
},
node: {
fs: 'empty'
},
resolve: {
extensions: [".js", ".jsx"]
},
plugins: [
new webpack.DefinePlugin({
'process.env.HOSTNAME': JSON.stringify("localhost"),
'process.env.PORT': JSON.stringify(1111),
})
]
};
现在我的 webpack 应该可以正常工作,因为我在不同的项目上使用相同的 webpack 配置,并且它在我需要的地方正确显示图像。
问题是您的 webpack 配置没有设置为加载图像,所以当它尝试解析.png时,它会死亡。您应该为file-loader
配置规则:
{
test: /.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {},
},
],
}
。或类似。
现在我的 webpack 应该可以正常工作,因为我在不同的项目上使用相同的 webpack 配置,并且它在我需要的地方正确显示图像。
不知道如何回答这个问题,只能说这似乎是不可能的,因为这个 webpack 配置根本不会处理图像。