Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Electron Introduction

Electron Introduction

Electron is an open-source framework that wraps Chromium (browser engine) + Node.js (server/system capabilities) into a desktop application shell, letting you use HTML/CSS/JS to write cross-platform desktop programs (Windows, macOS, Linux).

Key points:

Electron is developed and maintained by GitHub and was originally created to build the Atom editor.

In short:Electron = Chromium + Node.js + Native APIs


Why choose Electron

Electron lets web developers build desktop apps without learning a new language, greatly lowering the barrier to desktop development.

Electron's design philosophy is "Write Once, Run Everywhere".

Developers only need to write one codebase to generate applications for the three platforms Windows, macOS, and Linux.

Core advantages:


Application scenarios

Electron is suitable for developing the following types of desktop apps:

Unsuitable scenarios: projects extremely sensitive to CPU/GPU/memory, requiring the ultimate native experience, or mobile-first (such as large-scale graphics rendering, ultra-low-latency games).


What Electron can do

Electron provides rich desktop capabilities; the following are its main supported features:


Core concepts (technical points)

Understanding the following core concepts is key to mastering Electron development:


Security considerations

Electron has both browser and Node.js capabilities, so security configuration is critical.

Never directly enable in the renderer nodeIntegration: true, disabled by default to prevent XSS from executing arbitrary system commands.


Advantages and limitations of Electron

This section comprehensively analyzes Electron from both the advantages and limitations dimensions to help you make a sound technology choice.

Main advantages

The following are Electron's core competitive advantages over other desktop development solutions:

1. Convenience of cross-platform development

With Electron, developers can use the same codebase to generate apps for Windows, macOS, and Linux:

Example

// File path: main.js

// The same code can run on three platforms

const

{

app

,

BrowserWindow

}

=

require

(

'electron'

)

;

// Function to create the main window

function

createWindow

(

)

{

 

const

win

=

new

BrowserWindow

(

{

    width

:

800

,

 

// Window width (pixels)

    height

:

600

 

// Window height (pixels)

 

}

)

;

 

// Load a local HTML file

  win.

loadFile

(

'index.html'

)

;

}

// Create the window after app is ready

app.

whenReady

(

)

.

then

(

createWindow

)

;

Costs saved:

2. Advantages of the web technology stack

3. Powerful feature support

4. Active community and ecosystem

Main limitations

Understanding Electron's limitations helps judge whether it fits your project:

1. Performance overhead

Electron apps need to run both Chromium and Node.js, which brings extra performance overhead:

Native apps vs Electron apps:

Comparison Dimensions Native app Electron app
Memory Usage 10-30MB 80-200MB
Startup time < 1 second 2-5 seconds

2. Large installer size

Every Electron app must package the full Chromium and Node.js runtimes:

This means even a simple app's installer will not be smaller than 50MB.

3. Security considerations

Since Electron has both browser and Node.js capabilities, improper configuration may pose security risks:

4. Native experience differences

Although native UIs can be mimicked, differences remain in some aspects:

Trade-off recommendations

The following table helps you judge whether Electron fits your project requirements:

Factor Weight Description
Development efficiency High If the team has web experience, Electron is the most efficient
Cross-platform needs High When multi-platform support is needed, Electron is the preferred choice
Performance requirements Medium Acceptable for general apps except extreme-performance scenarios
Sensitivity to package size Medium 50-100MB is acceptable in modern network environments
Security requirements High Security best practices must be strictly followed

Comparison with other similar tools

Electron is not the only choice; the following is a comparison of mainstream desktop development solutions:

If you are a front-end/full-stack developer who needs toquickly deliver web products or tools to the desktop and directly use system capabilities, Electron is a highly productive, low-barrier choice.

But if you have strict requirements on size, memory, or the ultimate native experience, consider Tauri, Flutter, or native frameworks as alternatives.

- Core: Rust + system-native WebView (WebView2 / WebKit). - Pros: small size, low memory usage, good security, suitable for lightweight and performance-focused apps. - Suitable for: desktop apps wanting web technology but extremely small size or performance sensitivity. - Comparison: If you want to quickly reuse the Node.js ecosystem, Electron is more convenient; if you pursue small size, choose Tauri. - Similar origins to Electron (also Chromium + Node), but with a different API style. - The Electron community and tools are more active. - Extremely lightweight, uses the system WebView, with fewer features than Electron. - Better suited for simple tools or small desktop apps. - Uses Dart/Flutter rendering, with good native performance and high UI consistency. - Suitable for projects needing unified cross-platform UI/performance, but requires relearning a UI framework (not web technology). - A more native desktop development route, suitable for projects with high requirements on system integration, performance, and native experience.

Selection advice:


Common performance and size questions

The following are practical tips for optimizing Electron app performance and size:


Quick start example

Quickly understand Electron's basic structure through a minimal project.

Project file structure:



my-electron-app/

├─ package.json    # 项目配置与依赖

├─ main.js         # 主进程入口

├─ preload.js      # 预加载脚本(安全暴露 API)

└─ index.html      # 渲染进程界面

package.json(minimal configuration):

Example

{

  "name": "my-electron-app",

  "version": "0.1.0",

  "main": "main.js", // Specify the main process entry file

  "scripts": {

    "start": "electron ." // npm start launches the app

  },

  "devDependencies": {

    "electron": "latest" // Electron as a dev dependency

  }

}

main.js(main process):

Example

// File path: main.js

const

{

app

,

BrowserWindow

}

=

require

(

'electron'

)

;

const

path

=

require

(

'path'

)

;

// Create the main window

function

createWindow

(

)

{

 

const

win

=

new

BrowserWindow

(

{

    width

:

900

,

    height

:

600

,

    webPreferences

:

{

      preload

:

path.

join

(

__dirname

,

'preload.js'

)

,

 

// Preload script path

      contextIsolation

:

true

,

 

// Enable context isolation (recommended)

      nodeIntegration

:

false

   

// Disable Node integration for better security

   

}

 

}

)

;

  win.

loadFile

(

'index.html'

)

;

}

// Create the window after app is ready

app.

whenReady

(

)

.

then

(

createWindow

)

;

// macOS: do not quit the app when all windows are closed (follows macOS convention)

app.

on

(

'window-all-closed'

,

(

)

=>

{

 

if

(

process.

platform

!==

'darwin'

)

app.

quit

(

)

;

}

)

;

preload.js(controlled API exposure):

Example

// File path: preload.js

const

{

contextBridge

,

ipcRenderer

}

=

require

(

'electron'

)

;

// Expose safe APIs to the renderer via contextBridge

// The renderer can access them via window.electronAPI

contextBridge.

exposeInMainWorld

(

'electronAPI'

,

{

 

// Send messages to the main process (only whitelisted channels allowed)

  send

:

(

channel

,

data

)

=>

{

   

const

validChannels

=

[

'ping'

]

;

         

// Whitelist: allowed channels

   

if

(

validChannels.

includes

(

channel

)

)

{

      ipcRenderer.

send

(

channel

,

data

)

;

   

}

 

}

,

 

// Receive messages from the main process (only whitelisted channels allowed)

  on

:

(

channel

,

func

)

=>

{

   

const

validChannels

=

[

'pong'

]

;

         

// Whitelist: allowed channels

   

if

(

validChannels.

includes

(

channel

)

)

{

     

// Remove the event parameter, passing only business data to the callback

      ipcRenderer.

on

(

channel

,

(

event

,

...

args

)

=>

func

(

...

args

)

)

;

   

}

 

}

}

)

;

index.html(renderer process UI):

Example

 

   

Hello Electron

   

   

 

Listen for IPC in the main process (add to main.js):

Example

// File path: main.js (additional content)

const

{

ipcMain

}

=

require

(

'electron'

)

;

// Listen for ping messages from the renderer and reply with pong

ipcMain.

on

(

'ping'

,

(

event

,

data

)

=>

{

  console.

log

(

'Received ping, data:'

,

data

)

;

  event.

sender

.

send

(

'pong'

,

{

reply

:

'ok'

,

received

:

data

}

)

;

}

)

;

Run:



# Install dependencies

npm install



# Start application

npm start


Packaging and distribution

After development, you need to use packaging tools to distribute the app to users.

Comparison of common packaging tools:

Tool Function Applicable scenarios
Electron Builder Powerful, supports auto-update and multi-platform installers Production projects needing a complete distribution solution
Electron Forge Developer-friendly, integrates templates and build workflows Fast startup for new projects
electron-packager Only packages, no installer Simple packaging needs

Common packaging steps:

  1. Configure package.json the build field (or each tool's config).
  2. Use CI/CD to build for different platforms (Windows must be packaged in a Windows environment or use cross-compile services).
  3. Deploy an update server or use GitHub Releases + electron-updater.

Practical advice and best-practice checklist

The following advice comes from real project experience and helps you avoid common pitfalls:


When not to use Electron

Electron is not recommended in the following scenarios:


Recommended learning path and resources

Following this path step by step lets you systematically master Electron development:

  1. Learn basic Node.js and front-end (HTML/CSS/JS) / frameworks (React/Vue).
  2. Read the official Electron documentation (Main/Renderer/Preload/IPC/security guide).
  3. Build a minimal example (the one above) and experiment with IPC, file operations, window control.
  4. Learn and use packaging tools (Electron Builder / Forge).
  5. Read tutorials on security best practices, auto-updates, and code signing.
  6. Study architecture by referencing mature open-source Electron projects (e.g., VS Code source snippets).