Search code examples
webpackwebpack-dev-serverwebpack-file-loader

404 when fetching image with webpack


I'm following this link to add images to my bundle:

https://webpack.js.org/guides/asset-management/

I have the following files structure in my root folder:

index.html

index.js

images folder (with svg's)

This is my webpack.config.js

// Generated using webpack-cli https://github.com/webpack/webpack-cli

const path = require('path');

const isProduction = process.env.NODE_ENV === 'production';
const HtmlWebpackPlugin = require("html-webpack-plugin");

const stylesHandler = 'style-loader';



const config = {
    entry: './index.js',
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'index_bundle.js'
    },
    devServer: {
        open: true,
        historyApiFallback: true,
        host: 'localhost'
    },
    plugins: [
        new HtmlWebpackPlugin({
            title: 'Custom template',
            // Load a custom template (lodash by default)
            template: 'index.html'
        })
    ],
    module: {
        rules: [
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/i,
                type: 'images',
            },
        ]
    }
};


module.exports = () => {
    if (isProduction) {
        config.mode = "production";
    } else {
        config.mode = "development";
    }
    return config;
};

I'm using the following webpack modules:

    "webpack": "^5.64.4",
    "webpack-cli": "^4.9.1",
    "webpack-dev-server": "^4.6.0",
    "wepack-cli": "0.0.1-security"

In my js file, I'm trying to add an image to an SVG element by doing:

.attr('xlink:href', 'images/virtual-machine.svg')

But I'm getting 404.


Solution

  • Try using resource asset module

      rules: [
                {
                    test: /\.(png|svg|jpg|jpeg|gif)$/i,
                    type: 'asset/resource',
                },
            ]
    

    Now the webpack must be aware you are using this image. Following import should work.

    Make sure the path is correct as it will lookup path from the current folder

    import virtualMachineSvg from 'images/virtual-machine.svg'
    
    .attr('xlink:href', virtualMachineSvg)
    

    Or require

    const virtualMachineSvg = require('images/virtual-machine.svg');
    
    .attr('xlink:href', virtualMachineSvg)