Electron
Cross-platform desktop apps with JavaScript, HTML, and CSS.
Quick Start
// main.js
const { app, BrowserWindow, ipcMain } = require('electron');
function createWindow() {
const win = new BrowserWindow({
width: 1200,
height: 800,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: __dirname + '/preload.js',
},
});
win.loadURL('http://localhost:5173'); // or loadFile('dist/index.html')
}
app.whenReady().then(createWindow);
// IPC handler
ipcMain.handle('get-user-data', async () => {
return { name: 'Alice', role: 'admin' };
});
// preload.js
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('electronAPI', {
getUserData: () => ipcRenderer.invoke('get-user-data'),
});
When to Use
- Cross-platform desktop apps (Windows, Mac, Linux)
- Apps built with web frameworks (React, Vue, Svelte)
- Not for lightweight apps (better Tauri)
Step-by-Step Instructions
- Init:
npm init; npm install electron --save-dev - Create
main.jswith window creation - Create
preload.jsfor secure IPC - Build and package:
npx electron-builder
Dependencies
npm install electron --save-dev
npm install electron-builder --save-dev
Examples
Input: npm run start → Output: Native desktop window with web app
Resources
Troubleshooting
- App bloat from
node_modules— the build packed everything. Useelectron-builderfiles/asarand exclude dev dependencies. - Blank white screen — renderer crashed. Check DevTools console and
verify the preload script has
contextIsolation-safe IPC wiring. - App not restarting — main window destroys on close. Prevent
window-all-closedquit on macOS, or attach thebefore-quitlifecycle hook. - Native modules fail to load — ABI mismatch after a Node upgrade.
Rebuild with
electron-rebuildand pin the Electron ABI version.
Validation
- App window opens correctly
- IPC communication works
- App packages for target OS