'Webpack: 404 image not found

If I set image src in my html file, I am able to get the image. But when I use my script file to set the image src, the console keeps saying image not found(404). Why is that? Sorry this is my first time using webpack.

folder and files:

-dist(This folder is generated by webpack)
  -bundle.js
  -bundle.js.map
  -index.html
  -cat.jpg
-images
  -cat.jpg
-node_modules
-index.html
-index.js
-package.json
-webpack.dev.js
-webpack.prod.js

html:

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
  </head>
  <body>
      <h1>Hello world..</h1>
      <img class="image" src="#" alt="#">
  </body>
</html>

index.js:

const imageEl = document.querySelector('.image');
imageEl.src = './images/cat.jpg'; <--- If I manually put this path in the html image element src, 
                                          the image will show up but when I set it in this file the image 
                                          is not found.

console.log(imageEl);

webpack.dev.js:

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

module.exports = {
    mode: 'development',
    entry: './index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.js',
    },
    devServer: {
        contentBase: path.join(__dirname, 'dist'),
        open: true,
        port: 8080
    },
    devtool: 'source-map',
    module: {
        rules: [
            {
                test: /\.(png|jpe?g|gif|svg)$/i,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: '[name].[ext]',
                            esModule:false,
                            publicPath: 'images'
                        }
                    },
                ],

            },
            {
                test: /\.html$/i,
                loader: 'html-loader'
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: './index.html'
        })
    ]
}

(webpack.prod.js is the same just without the devServer)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source