徽标图像无法在React应用中呈现。模块解析失败

时间:2019-02-03 00:12:22

标签: javascript reactjs react-native

我有一个rect组件。我想在组件中渲染图像。我在尝试加载徽标并将其呈现到组件中时遇到问题。我解析失败,我不确定为什么会收到此错误:

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配置,并且可以在需要的位置正确显示图像。

1 个答案:

答案 0 :(得分:2)

问题是您的Webpack配置未设置为加载图像,因此当它尝试解析.png时,它就死了。您应该为file-loader配置规则:

 {
    test: /\.(png|jpg|gif)$/,
    use: [
      {
        loader: 'file-loader',
        options: {},
      },
    ],
  }

...或类似的

  

现在,我的webpack应该可以正常工作,因为我在不同的项目上使用了相同的webpack配置,并且可以在需要的位置正确显示图像。

除了说这似乎不太可能之外,不确定如何回答这个问题,因为此webpack配置根本无法处理图片。