使用webpack加载器在React中加载图像

时间:2018-07-18 08:18:57

标签: reactjs webpack

我无法在React组件中显示图像。经过多次试验(尝试thisthisthisthisthisthisthis和{{3 }}),只有错误,我正在寻求帮助。我在开发阶段(而不是生产阶段)。

我仍然收到此错误:

Module parse failed: /project/src/images/net.png Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.
(Source code omitted for this binary file)

组件

import thumbnail from '../images/net.png';

<img src={thumbnail}/>

Webpack配置:

devtool: 'cheap-module-eval-source-map',
entry: [
    'eventsource-polyfill',
    'webpack-hot-middleware/client',
    './src/index'
],
target: 'web',
output: {
    path: path.resolve(__dirname, 'dist'),
    task `npm run build`.
    publicPath: 'http://localhost:3000/',
    filename: 'bundle.js'
},
devServer: {
    contentBase: './src'
},
plugins: [new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin()],
module: {
    rules: [
        {
            test: /\.js$/,
            include: path.join(__dirname, 'src'),
            loader: 'babel-loader'
        },
        {
            test: /(\.css)$/,
            use: [
                'style-loader',
                {
                    loader: 'css-loader',
                    options: { sourcemap: true }
                }
            ]
        },
        {
            test: /\.(svg|png|jpg|jpeg|gif)$/,
            include: './src/images',
            use: {
                loader: 'file-loader',
                options: {
                    name: '[path][name].[ext]',
                    outputPath: paths.build
                }
            }
        }
    ]
}

目录结构

Project
-- src
-----components
-----images
-----index.js

如何显示图像?

此处的示例代码:this 参见/src/components/home/HomePage.js

如何查看主页上的图像?

4 个答案:

答案 0 :(得分:0)

您尝试过此webpack配置

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

答案 1 :(得分:0)

我改用url-loader

  {
    test: /\.(png|jpg)$/,
    use: {
      loader: 'url-loader',
      options: {
        limit: 25000 // Max file size = 25kb
      }
    }
  }

我不确定。但是,我认为您应该首先将其安装为devDependencies,例如yarn add -D url-loader

答案 2 :(得分:0)

test: /\.(jpe|jpg|woff|woff2|eot|ttf|svg)(\?.*$|$)/,

尝试将其与file-loader加载程序一起使用。 注意(?。* $ | $),而不是普通的 $

答案 3 :(得分:0)

{           测试:/.(png|jp(e*)g|svg|gif)$/,           采用:[{             加载程序:“ url-loader?limit = 8192”           }]         }

我在webpack中使用url-loader加载了png。您还需要重建webpack。