How to add an icon to electron application
Solution 1
Simple solution
const nativeImage = require('electron').nativeImage;
var image = nativeImage.createFromPath(__dirname + '/public/img/logo.png');
// where public folder on the root dir
image.setTemplateImage(true);
// Create the browser window.
win = new BrowserWindow({
width: 1179,
height: 754,
backgroundColor: '#ffffff',
transparent: false,
icon: image
})
Solution 2
inside the main.js
mainWindow = new BrowserWindow({width: 800, height: 600,icon: __dirname + '/icon.ico'});
and on the installer, if you are using electron-builder
"devDependencies": {
"electron": "^1.4.15",
"electron-builder": "^12.3.1"
},
make a folder on the root and named build inside that folder add your icon.ico
sometimes you need to restart the electron or build the app 2 times
Solution 3
Following worked for me. To display the app icon in the taskbar, you can update the icon on the fly in main.js (if using typescript then main.ts)
win.setIcon(path.join(__dirname, '/src/assets/logo-small.png'));
Worth to mention __dirname
points to same directory as package.json
Tim
Updated on June 06, 2022Comments
-
Tim almost 2 years
I've got my electron build files for a win .exe and installer but the icons aren't mine. In my main.js file, I have code to attach the icon but I can only make it work inside of the createWindow function. Outside the function, I get an error message. The .exe will run and I get my icon, though it's I get an error in doing so; the installer won't work at all. I've tried going through several tutorials but none of them solve this problem.
main.js
const {app, BrowserWindow, Tray} = require('electron') const path = require('path') const url = require('url') let win function createWindow () { const appIcon = new Tray('icon/app.png') win = new BrowserWindow({ width: 1920, height: 1080, icon: 'icon/app.ico' }) console.log(appIcon, win) win.loadURL(url.format({ pathname: path.join(__dirname, 'app/app.html'), protocol: 'file:', slashes: true })) win.on('closed', () => { win = null }) } app.on('ready', createWindow) app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { if (win === null) { createWindow() } })
package.json
{ "name": "myapp", "version": "1.0.0", "description": "MyApp", "private": true, "main": "main.js", "build": { "appID": "myapp", "productName": "MyApp", "icon": "icon/app.ico" }, "scripts": { "start": "electron ." , "package": "", }, "author": "Me", "license": "ISC", "devDependencies": { "electron": "^1.6.1" } }
I'm not sure what to do from here.
-
Hawkeye64 over 5 yearsThis worked for me. Did not need to use
image.setTemplateImage(true);
. -
MrAn3 over 3 yearsOn several places it says that using a path string is enough. But just until I used nativeImage got it working on Ubuntu.