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/imac/Desktop/fakeeh/imgs/logo.png Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type.

Here is webpack config:

const path = require('path');


module.exports = {
  // the entry file for the bundle
  entry: path.join(__dirname, '/client/src/app.jsx'),

  // the bundle file we will get in the result
  output: {
    path: path.join(__dirname, '/client/dist/js'),
    filename: 'app.js',
  },

  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"]
      }
    }],
  },

  // start Webpack in a watch mode, so Webpack will rebuild the bundle on changes
  watch: true
};

Much appreciated!!

Abdulrahman Mushref
  • 1,012
  • 2
  • 18
  • 40

6 Answers6

75

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' }]
  },
Arman Ortega
  • 3,003
  • 1
  • 30
  • 28
  • 6
    It mentions file-loader and url-loader in the npm install, but in the webpack config, only url-loader is mentioned. Why is that? Does url-loader use file-loader behind the scenes? – redfox05 Jun 03 '20 at 15:59
  • 1
    @redfox05 it seems that url-loader might use file-loader behind the scenes. I attempted to follow instructions per webpack docs, https://webpack.js.org/loaders/url-loader/ and only added 'url-loader' and I received an error stating that 'file-loader' was not found. Installed 'file-loader' and everything worked as it should. – Alexiz Hernandez Jan 06 '21 at 06:55
  • I feel compelled to note that the parameter "?limit=100000" isn't supported in this format anymore and you need to specify a new field called "options" with the limit defined there instead. Therefore, the value for loader would simply be 'url-loader' – vbguyny Dec 02 '21 at 21:50
  • While still helpful, this answer is outdated for a few syntactical reasons. For example, you no longer can do the line `loader: "style-loader!css-loader"`; you have to separate the two packages into an array, like so: `loader: ["style-loader", "css-loader"]`. – JCollier Jul 19 '22 at 15:58
  • Another thing to watch out for: Webpack 5 doesn't need you to be using url-loader anymore. See https://stackoverflow.com/questions/68575859/webpack-file-loader-does-not-load-background-image and https://webpack.js.org/guides/asset-management/#loading-images – JCollier Jul 20 '22 at 00:54
18

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",
    }],
  },
Prakash Sharma
  • 15,542
  • 6
  • 30
  • 37
  • @PrakashSharma, thank you, I thought mine did not work because it was legacy and that was about a year ago, only to find out today that it does work by following your instructions. – Daniel May 09 '19 at 16:37
9

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')} />
philippe_b
  • 38,730
  • 7
  • 57
  • 59
5

these two steps worked for me

Asset Resource Loader ("webpack": "^5.70.0")

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.jsx',
  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.js',
    assetModuleFilename: '[name][ext]',      // (2)
  },
  resolve: {
    extensions: ['.jsx', '.js'],
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: ['babel-loader'],
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.(png|jpe?g|gif|svg)$/i,       // (1)
        type: 'asset/resource',
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html',
    }),
  ],
};
kirill-petrov
  • 71
  • 1
  • 3
0

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

If include property is defined, make sure it contains the path of the folder which contains the image. For me, that was the issue.

{
    test: /\.(png|jpg|ttf|eot|svg|woff(2)?)(\S+)?$/,
    include: [/react-notifications/, /goodtables-ui/, /@mdi\/font/, /clear-ui/],
    use: ['file-loader']
}
Sushil Kumar
  • 1,401
  • 2
  • 14
  • 27