javascript - 徽标图像无法在反应应用程序中呈现。模块解析失败
问题描述
我有一个矩形组件。我正在尝试在组件中渲染图像。当我尝试将我的徽标加载并呈现到组件中时,我遇到了一个问题。我遇到了解析失败,我不确定为什么会收到此错误:
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>
)
}
}
标志的路径是正确的
这是我的 webpack:
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 配置,并且它可以在我需要的地方正确显示图像。
Not sure how to answer this except to say that it doesn't seem possible, as this webpack config simply won't handle images.
推荐阅读
- google-sheets - 需要谷歌查询只显示大于单元格值的项目总和,另一个查询根据选择对值求和
- java - 在单线程上运行的弹簧执行器
- javascript - D3.js 和弦图 - 使和弦接触拉开的弧线
- python - Celery、flask 和 Docker - 日志和运行任务的问题
- java - java中的访问修饰符与示例?
- c - 在 C 中:如何打印函数参数
- c++ - 用于快速求解线性系统的 C++ Eigen
- swift - 可以在 Swift 中将 userdefaults plist 导出为电子邮件附件吗?
- python - Python - 启动烧瓶时找不到依赖项目的模块
- oracle - 在 Oracle APEX 中启用 SSO 登录