IMAGE: You may need an appropriate loader to handle this file type

后端 未结 4 1303
温柔的废话
温柔的废话 2020-12-05 17:45

I can\'t figure what is the proper loader to load images in ReactJS webpack,

May you give me a hand? I get this error:

Module parse failed: /Users/im         


        
相关标签:
4条回答
  • 2020-12-05 18:05

    With Webpack 3, you can use url-loader as follow:

    Install url-loader:

    npm install --save url-loader
    

    Then, in your Webpack config:

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

    Finally, in your code:

    <img src={require('./path/to/image.png')} />
    
    0 讨论(0)
  • 2020-12-05 18:17

    Sometimes the solution is simpler and right in front of you.

    I immediatly started to google for this issue. But I was missing jpg extention in the test.

    So.. my test is:

    test: /.(png|woff(2)?|eot|ttf|svg|gif|jpe?g)(\?[a-z0-9=\.]+)?$/

    0 讨论(0)
  • 2020-12-05 18:19

    I also encountered this problem too and I've found a workaround.

    First, you need to install the two loaders(file-loader, url-loader). e.g. $ npm install --save file-loader url-loader

    If you want to support the css. Make sure you install the style loaders. e.g., $ npm install --save style-loader css-loader

    Next, you update the webpack config, kindly check below my sample configurations. Hope it helps.

      module: {
        loaders: [{
          test: /.jsx?$/,
          loader: 'babel-loader',
          exclude: /node_modules/
        }, {
          test: /\.css$/,
          loader: "style-loader!css-loader"
        }, {
          test: /\.(jpe?g|png|gif|woff|woff2|eot|ttf|svg)(\?[a-z0-9=.]+)?$/,
          loader: 'url-loader?limit=100000' }]
      },
    
    0 讨论(0)
  • 2020-12-05 18:23

    You can use file-loader. You need to install it first using npm and then edit your webpack config like this

    module: {
    
        // apply loaders to files that meet given conditions
        loaders: [{
          test: /\.jsx?$/,
          include: path.join(__dirname, '/client/src'),
          loader: 'babel-loader',
          query: {
            presets: ["react", "es2015", "stage-1"]
          }
        },
        {
          test: /\.(gif|svg|jpg|png)$/,
          loader: "file-loader",
        }],
      },
    
    0 讨论(0)
提交回复
热议问题