close

How to load image files with webpack file-loader

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to load image files with webpack file-loader in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to load image files with webpack file-loader ?

  1. How to load image files with webpack file-loader ?

    to load image files with webpack file-loader Install file loader first:
    $ npm install file-loader --save-dev
    And add this rule in webpack.config.js
    { test: /\.(png|jpg|gif)$/, use: [{ loader: 'file-loader', options: {} }] }

  2. How to load image files with webpack file-loader ?

    to load image files with webpack file-loader Install file loader first:
    $ npm install file-loader --save-dev
    And add this rule in webpack.config.js
    { test: /\.(png|jpg|gif)$/, use: [{ loader: 'file-loader', options: {} }] }

Method 1

I had an issue uploading images to my React JS project. I was trying to use the file-loader to load the images; I was also using Babel-loader in my react.

I used the following settings in the webpack:

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "file-loader?name=app/images/[name].[ext]"},

This helped load my images, but the images loaded were kind of corrupted. Then after some research I came to know that file-loader has a bug of corrupting the images when babel-loader is installed.

Hence, to work around the issue I tried to use URL-loader which worked perfectly for me.

I updated my webpack with the following settings

{test: /\.(jpe?g|png|gif|svg)$/i, loader: "url-loader?name=app/images/[name].[ext]"},

I then used the following command to import the images

import img from 'app/images/GM_logo_2.jpg'
<div className="large-8 columns">

      <img  style={{ width: 300, height: 150 }} src={img} />
</div>

Method 2

Install file loader first:

$ npm install file-loader --save-dev

And add this rule in webpack.config.js

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

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment