lomse
lomse

Reputation: 4165

Unable to load image using Webpack 5

I'm using webpack 5 to bundle an embeddable widget. I can't seem to load an image created on the fly.

const img = document.createElement('img');
img.src = 'assets/doggo.svg';

http://localhost:8080/assets/doggo.svg gives 404

In my webpack.config.js I have the following:

module: {
         rules: [
            // Typecript
            {
               test: /\.ts|\.tsx$/,
               use: 'awesome-typescript-loader',
               include: __dirname
            },
            // Images
            {
               test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
               type: 'asset/resource',
            },
            // Fonts and SVGs
            {
               test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
               type: 'asset/inline',
            },
         ],
      },

Below is my file structure:

├── package.json
├── postcss.config.js
├── src
│   ├── index.ts
│   ├── assets
│   ├── index.html
│   ├── index.ts
│   ├── types.d.ts
│   └── utils
├── tsconfig.json
├── webpack.config.js
└── yarn.lock

Upvotes: 1

Views: 630

Answers (1)

lomse
lomse

Reputation: 4165

The approach below seems to work.

import doggoImg from './assets/doggo.svg';

const img = document.createElement('img');
img.src = doggoImg;

const container = document.createElement('div');

container.appendChild(img);

Upvotes: 1

Related Questions