使用React导入图像时出现错误

时间:2020-02-11 07:28:42

标签: javascript reactjs webpack webpack-4

我如下导入图像:

import StepIcon from '../../public/images/icon_step.png'

,它没有问题,但是当我运行build时,出现下面的错误,猜想我必须修复webpack设置,但我不知道。我该如何解决这个问题?

错误

 error  in ./public/images/icon_step.png

Module build failed (from ./node_modules/file-loader/dist/cjs.js):
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be one of type string, Buffer, TypedArray, or DataView. Received type function
    at Hash.update (internal/crypto/hash.js:64:11)
    at getHashDigest (/mnt/c/Users/wbvco/Desktop/Project Baby/styled-react-boilerplate/node_modules/loader-utils/lib/getHashDigest.js:48:8)
    at url.replace (/mnt/c/Users/wbvco/Desktop/Project Baby/styled-react-boilerplate/node_modules/loader-utils/lib/interpolateName.js:96:11)
    at String.replace (<anonymous>)
    at Object.interpolateName (/mnt/c/Users/wbvco/Desktop/Project Baby/styled-react-boilerplate/node_modules/loader-utils/lib/interpolateName.js:93:8)
    at Object.loader (/mnt/c/Users/wbvco/Desktop/Project Baby/styled-react-boilerplate/node_modules/file-loader/dist/index.js:27:36)

 @ ./src/components/signupstep.js 35:0-57 511:11-19
 @ ./src/pages/signup.js 
 @ ./src/app.js
 @ ./src/index.js
 @ multi react-hot-loader/patch ./src/index.js

Webpack设置

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

1 个答案:

答案 0 :(得分:0)

我认为这是由于图片相对路径问题引起的,您可以尝试以下方法吗?

  1. 您应该遵循的简单方法,有关更多信息,请参见here

  2. 通过使用webpack

请按如下所示更新Webpack

module: {
  rules: [
    {
      test: /\.(jpe?g|gif|png|svg)$/i,
      use: [
        {
          loader: 'url-loader',
          options: {
            limit: 10000
          }
        }
      ]
    }
  ],
},

然后您可以从公用文件夹导入图像以响应组件

import image from '../../public/assets/images/logo.png'

<img src={image}/>
  1. 通过使用require方法

  2. 您还可以通过安装url-loader和file-loader来尝试

    npm install url-loader文件加载器--save-dev

然后将Webpack配置更新为

module: {
    loaders: [
      { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192' }
    ]
} 

最后

<img src={require('./PATH_TO_IMAGE/IMAGE.png')}/>