Adding local image to widget

I want to add an image that’s part of the extension directory structure to a widget. I tried using the HTML img tag in the node of the widget but looks like the path to the image is not being resolved correctly. Can someone help me in fixing this issue? Where should the image be present in the folder structure and how do I reference it in my widget code?


Without a code example, it’s hard to say more, but embedding arbitrary content can use file-loader (and in v4, assets), usually picked up by the default rules. Assuming typescript:

// extension.ts
import * as img from '../../style/img.png'

What comes out of that depends on a few factors: you might get a URL or a base64 encoded string, you’ll have to do some interactive logging to find out. If you want to force them, you can use the !!file-loader!, !!raw-loader! or !!url-loader! prefixes to the import to force a particular thing, e.g. if you want to modify the bytes in some way.

Also, again assuming typescript, you may need to add some typings as well.

// typings.d.ts
declare module "*.png" {
  const value: any;
  export = value;
1 Like

Thank you @bollwyvl for the solution. Sorry for not providing the code earlier, here’s the sample code I’m trying to implement:

export class BannerWidget extends Widget {
    constructor(options={node:document.createElement('div')}) {

        this.node.innerHTML = `<img src='sample.png'></img><span style='margin-left:20px'>Sample</span>`;

The idea here is to have a small banner in my extension that has an image embedded and some text next to it. As per your approach, if I import the image in my extension code, how do I embed it in my widget?

If you’re bent on string interpolation, it would be something like

import * as img from '../../style/img.png'

// ...

  this.node.innerHTML = `<img src='${img}' />`;

Though as i said, it might be base64 encoded, and would need to be a properly-formatted data url.