How to add an icon to electron application

Tim picture Tim · Mar 9, 2017 · Viewed 16.3k times · Source

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.

Answer

Shashwat Gupta picture Shashwat Gupta · Sep 26, 2018

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
    })