1

We're trying to improve our build system to rely less on relative path imports, and one area we need to work on this for is image loading. So we're trying to do something like this, loading the images in with Electron's nativeImage:

import { nativeImage } from 'electron';
import ourImage from 'our-images/src/ourImage.png' 

console.log(ourImage) // Outputs 14ad9a9efa18beb2868a.png

const trayIcon = nativeImage.createFromPath(ourImage); // Blank icon appears - no error message
const trayIcon = nativeImage.createFromBuffer(ourImage); // App crashes: "Error: buffer must be a node Buffer" - even if we load the file using `type: asset/source` -- https://webpack.js.org/guides/asset-modules/

Is there some way to use this pattern in Electron with Webpack? Or are we forced to use require() and relative paths? We had originally tried require.resolve() to use a path instead of creating a nativeImage, but unfortunately it doesn't work consistently in the packaged app.

Slbox
  • 10,957
  • 15
  • 54
  • 106

1 Answers1

3

You can use a custom generator with your asset like so:

{
  test: /\.(bin|raw|png|ico|svg|jpg|jpeg|gif)$/,
  type: 'asset/inline',
  generator: {
    dataUrl: content => content
  }
}

This will allow you to import your icon directly. It will be imported as a "Buffer like object", but won't be an instance of one, you must convert the imported result to a buffer to use it with electron's nativeImage, like so

import importedIcon from './assets/icon.png';

const trayIcon = nativeImage.createFromBuffer(Buffer.from(importedIcon));
wizebin
  • 730
  • 5
  • 15
  • 1
    To see this in action you can see my open source electron-react yeoman generator https://github.com/wizebin/generator-electron-react – wizebin Dec 11 '21 at 23:52
  • How does this interact with Electron's support for high DPI images? Will they still be loaded as intended? https://www.electronjs.org/docs/latest/api/native-image#high-resolution-image – Slbox Dec 16 '21 at 22:29
  • Thank you, this worked for me. Note: I had to make sure no other tests included the file I wanted to read as buffer. – Thijmen Mar 14 '22 at 22:09