introduce

Build cross-platform desktop applications using JavaScript, HTML, and CSS

  • Based on Chromium and Node.js
  • Allows you to build applications using HTML, CSS and JavaScript
  • Open source
  • Cross-platform (Windows, Mac, Linux)

Atom, Postman, Notion, Vscode, etc are all developed with Electron

Quick learning

manual

1. Create a file and initialize it

mkdir Hello-world && cd Hello-world
npm init -y
Copy the code

Remember to modify the entry file and create the entry file main.js in the root directory

// package.json
{
  ...
  "main": "main.js",
  ...
}
Copy the code

2. Install the electron dependency

npm install --save-dev electron
Copy the code

3. Add a start command under the scripts field in the package.json configuration file

// package.json
{
  "scripts": {
    "start": "electron ."
  }
}
Copy the code

4. Run

npm start
Copy the code

5. Blank because there is no content. Write AN HTML

<! -- index.html --> <! DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World! </title> </head> <body> <h1>Hello World! </h1> <p>Welcome to your Electron application.</p> </body> </html>Copy the code

6. Modify the main entry main.js code

Const path = require('path') // app: the module that controls the application event lifecycle // BrowserWindow: Create and manage the application window module const {app, BrowserWindow } = require('electron') function createWindow () { const mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload. Js)}}) mainWindow. LoadFile (' index.html') / / open development tool mainWindow webContents. OpenDevTools ()} / / in the Electron, The browser window can only be created after the ready event of the app module is fired. // A vue-like life cycle will initialize app.whenReady().then(() => {createWindow() // Mac after Electron Logic shutdown only hides command + Q before exiting app.on('activate', The function () {if (BrowserWindow getAllWindows (). The length = = = 0) createWindow ()})}) / / Windows and Linux closes the window will be completely out of the window app.on('window-all-closed', function () { if (process.platform ! == 'darwin') app.quit() })Copy the code

The scaffold

# clone sample project warehouse git clone https://github.com/electron/electron-quick-start # CD electron - quick - start to enter the warehouse # NPM up and running install && npm startCopy the code

If the installation is too slow, you can set taobao source

Latest Taobao source address:

Set # Npm taobao source Npm config set registry https://registry.npmmirror.com/ # check whether modify success Npm config get registryCopy the code

Use Taobao source when running if prompt this error

Address the problem

throw new Error('Electron failed to install correctly, please delete node_modules/electron and try installing again')
Copy the code

Then, set the source address of the electron mirror

npm config set electron_mirror https://cdn.npm.taobao.org/dist/electron/
Copy the code

packaging

Note: Icon format icon format used on Windows icon. Ico Is used on Mac icon. Icns

Use the electron – forge

The installation

npm install --save-dev @electron-forge/cli
npx electron-forge import
Copy the code

use

npm run make
Copy the code

Config => Forge => packagerConfig in package.json file

Use the electron – packager

The installation

npm install --save-dev electron-packager
Copy the code

use

npx electron-packager <sourcedir> <appname> --platform=<platform> --arch=<arch> [optional flags...]
Copy the code

Specific parameters: github.com/electron/el…

Generate the desktop application directly from the website

Create the initialization file manually or scaffolding as shown above

Modify the main js

const { app, BrowserWindow, Menu } = require('electron') function createWindow() { const win = new BrowserWindow({ autoHideMenuBar: true, show: False, // Whether to display the window, if not, open the fullscreen object with.show() : False,}) /** * Optimized load mode When the page is loaded directly in the window, the user will see the incomplete page, * This is not a good native app experience, the display window will have no visual flicker after using this event */ win.on('ready-to-show', () = > {win. The show ()}) / / / / win generate debug toolbar webContents. OpenDevTools () / / window to maximize win. Maximize () / / loading remote URL (URL) Win.loadurl ('https://www.iyouhun.com/') // Set menu bar const template = [{label: 'file ', submenu: [{label:' about ', role: 'about',}, {label: 'close ', Accelerator: 'Command ', click: () => { win.close() }, }, ], }, ] const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) } app.on('ready', App. on('window-all-closed', () => {if (process.platform! == 'darwin') { app.quit() } }) app.on('activate', The if () = > {/ / Mac logic (BrowserWindow. GetAllWindows (). The length = = = 0) {createWindow ()}})Copy the code

Advantages and disadvantages of Electron

advantages

  • Native interface (menus, message reminders, system tray, etc.).
  • Easy to get started, can use react, Vue and other front-end frameworks, can easily migrate front-end components, build beautiful desktop applications.
  • Convenient thermal update
  • Easy to debug and test
  • Electron uses node.js. As a result, you can import many modules in Chrome applications that are not easy to use
  • Electron is much better

disadvantages

  • Not suitable for developing lightweight applications. Even a Electron project framework includes the Chromium kernel.
  • Compared to desktop applications developed in c++, the performance is far worse.
  • The startup speed is slow.
  • Each window is a new process and takes up a lot of memory.

Electron and PWA

  • availability
    • Electron cannot be installed on any device
    • The PWA doesn’t even need an Internet as long as it has an Internet connection and a browser memory
  • performance
    • PWA has better performance, Service Worker, and reduced load time
  • Take up the space
    • The Electron package is too large, after all, each package contains the Chromium kernel
  • security
    • The Electron packet is fully readable without any obtruded encryption because it is stored locally
    • PWA is stored on the server and can only be transferred over HTTPS
  • Update and integration
    • Both can be asynchronously updated on the server
  • interaction
    • Electron can call the native interface

Electron and Flutter

  • To fit the difficulty
    • Electron: Basic HTML, CSS, JS
    • Flutter: Learn the Dart language
  • focus
    • Electron is more PC oriented
    • Flutter is more mobile