1

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.

Ace
  • 831
  • 2
  • 8
  • 28
  • The string literal path 'images/virtual-machine.svg' won't just work. You need to import asset via `import` or `require` – Józef Podlecki Dec 07 '21 at 11:15
  • @JózefPodlecki - I'm probably missing some info but when looking at http://localhost:8080/webpack-dev-server, I don't see any images folder so if I use require via code, I assume it would also fail. – Ace Dec 07 '21 at 11:20
  • Now Im not sure if `type: 'images'` would even work. What webpack version are you using? In webpack 5 there is `type: 'asset/resource'` which will work only once you import it directly in the code – Józef Podlecki Dec 07 '21 at 11:24
  • @JózefPodlecki - updated my post with webpack packages – Ace Dec 07 '21 at 11:50

1 Answers1

1

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)
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50