This article has participated in the third “topic writing” track of the Denver Creators Training Camp. For details, check out: Digg Project | Creators Training Camp third is ongoing, “write” to make a personal impact.

Electron

Electron is a framework for creating cross-platform desktop applications using Web technologies such as JavaScript, HTML and CSS. It can create desktop applications using pure JavaScript calling rich native (operating system) APIs, Think of it as a variant of Node.js, but for desktop application development.

The following is an Electron application development architecture and tool chain:

Environment configuration

  1. To install the latest version of Node.js, select Node.js Runtime, NPM Package Manager, and Add to PATH.

  2. Command line to confirm the installation

Print the node.js version information
node -v

Print the version information of NPM
npm -v
Copy the code
  1. Use a js editor, VSCode is recommended

  2. Install taobao NPM image

npm install -g cnpm --registry=https://registry.npm.taobao.org
Copy the code
  1. Alternatively, use Yran package management
npm install -g yarn
Copy the code

Build the first Electron app

Electron can be seen as a stripped-down version of the Chromium browser controlled by JavaScript. Its development tool chain is also based on Node, and its development is a complete Node project development process.

The directory structure

The Electron Application is essentially a Node.js application. The entry point for the application is a package.json file.

A basic Electron application will typically have the following directory structure:

├─ download.txt └─ download.txt └─ download.txtCopy the code

Initialization and installation

  • npm initInitialize a new Electron application
$ mkdir my-electron-app && cd my-electron-app
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency inthe package.json file. Press ^C at any time to quit. package name: (app1) firstelectronapp version: Description: First Electron application Entry point: (index.js)test command:
git repository:
keywords:
author:
license: (ISC)
About to write to E:\vscode\Electron\App1\package.json:

{
  "name": "firstelectronapp"."version": "1.0.0"."description": "First Electron application."."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": ""."license": "ISC"
}


Is this OK? (yes)
Copy the code

NPM creates a basic package.json file. Main is the startup script of the application and is executed in the main process.

When package.json defaults to the main field, Electron will attempt to load the index.js file.

Like the Node application, you can add a start script that specifies the current project directory to be executed in Electron:

{
  "name": "firstelectronapp"."version": "1.0.0"."description": "First Electron application."."main": "index.js"."scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"."start": "electron ."}}Copy the code
  • Install the Electron

It is recommended to install Electron as a development dependency of the APP. Different apps can use different versions of Electron

cnpm install --save-dev electron
Copy the code

The Electron installation reported an error

The error reported by Electron during installation is as follows:

Install fail! Error: EISDIR: illegal operation on a directory, symlink 'E: \ vscode/Electron/App1 / node_modules \ _ @ [email protected] @ @ types \ node' -> 'E: \ vscode/Electron/App1 / node_modules \ _electron @ 7.1.11 @ Electron \ node_modules \ @ types \ node'
Error: EISDIR: illegal operation on a directory, symlink 'E: \ vscode/Electron/App1 / node_modules \ _ @ [email protected] @ @ types \ node' -> 'E: \ vscode/Electron/App1 / node_modules \ _electron @ 7.1.11 @ Electron \ node_modules \ @ types \ node'Npminstall version: 3.27.0Copy the code

This problem is usually caused by FAT32 disk format, change the disk format to NTFS, delete node_modules and reinstall.

How do I convert a FAT32 disk to NTFS

For example, convert disk E to NTFS format: convert E: /FS:NTFS /X.

Simple Electron

Introduction of Electron module

const electron = require('electron')
Copy the code

The functions provided by the ELECTRON module are exposed through the namespace. For example, electron. App manages the life cycle of the electron application, and the electron.BrowserWindow class creates Windows.

Create a simple window

  • Add the following code to create a window in the main entry file
const { app, BrowserWindow } = require('electron')

function createWindow() {
    // Create a browser window
    let win = new BrowserWindow({
        width: 800.height: 600.webPreferences: {
            nodeIntegration: true}})// Load the index.html file. The loaded file must be in the current project directory, the outer directory will not be able to load
    win.loadFile('index.html')
}

app.on('ready', createWindow)
Copy the code
  • Index.html for a simple Hello message and a popover
<div>
    <span>Hello Eletron</span>
    <button id="btn">Click on the</button>
</div>
<script type="text/javascript">
    var btn = document.getElementById("btn");
    btn.addEventListener("click".function () {
        alert("Hello, welcome to Electron!")})</script>
Copy the code
  • npm startStart the Electron program to check the effect:

Optimized Electron program

You typically create Windows in the main entry file and handle any system events you might encounter in your program.

Here, add the following features to the main entry file: Open developer tools, handle window closing events, and rebuild Windows when the macOS user clicks on the dock icon:

const { app, BrowserWindow } = require('electron')

// Keep a global reference to the window object, if not, when the JavaScript object is called
// The window object will be closed automatically during garbage collection.
let win

function createWindow() {
    // Create a browser window.
    win = new BrowserWindow({
        width: 800.height: 600.webPreferences: {
            nodeIntegration: true}})// Load the index.html file
    win.loadFile('index.html')

    // Open the developer tool
    win.webContents.openDevTools()

    // This event is raised when the window is closed.
    win.on('closed'.() = > {
        // Unreference the window object. If your application supports multiple Windows,
        // It is common to store multiple window objects in an array,
        // In the meantime, you should delete the corresponding element.
        win = null})}// Electron will be initialized and ready
// This function is called when the browser window is created.
// Parts of the API can only be used after the ready event is triggered.
app.on('ready', createWindow)

Exit when all Windows are closed.
app.on('window-all-closed'.() = > {
    // On macOS, unless the user explicitly exits with Cmd + Q,
    // Otherwise, most apps and their menu bar remain active.
    if(process.platform ! = ='darwin') {
        app.quit()
    }
})

app.on('activate'.() = > {
    // On macOS, when you click the Dock icon and no other Windows open,
    // Usually a window is recreated in the application.
    if (win === null) {
        createWindow()
    }
})

// In this file, you can write the rest of the application's main process code.
// It can also be split into several files and imported with require.
Copy the code

Since the window cannot be created before the Ready event, listeners for the Activate event can be handled in the Ready. As follows:

The latest version of Electron implements the Ready event based on Promise, which is recommended as follows:

app.whenReady().then(() = > {
  createWindow()

  app.on('activate'.function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})
Copy the code

Debug the Electron main process

For code debugging on the inside of the window, you can use DevTools (developer tools) in the Electron browser window.

But for main process debugging, you must rely on the –inspect and — inspect-BRk switches supplied by Electron. See debugging main process for details

Debug the main process in vscode

  1. As follows, add the debug item to the scripts in the package.json file.
{
 "scripts": {
    "start": "electron ."."debug": "electron --inspect=5858 ."}}Copy the code
  1. Below, under the debug run menu of vscode, create a new onelaunch.jsonFile and add the “Attach to process” configuration item.

Specify “request” as “attach”, port inspect as in the script configuration above.

Json file:

        {
            "type":"node"."request": "attach"."name": "Attach to process"."port": 5858."address": "localhost"
        }
Copy the code
  1. yarn debugRun the electron program
$YARN debug YARN run V1.21.1 $inspect=5858. Debugger listening on Ws: / / 127.0.0.1:5858 / c115b336 - f5d4 a7-42 f4-85-3 ef807d9d8a4 Forhelp, see: https://nodejs.org/en/docs/inspector
Copy the code
  1. Electron performinspectAfter that, run the attach to process TAB under debug and run in vscode to debug the main process.

Enable the debugging of the main process

  • --inspect=[port], such as:electron --inspect=5858 your/app
  • --inspect-brk=[port], and--inspectorSame, but js suspends execution on the first line of the run.

The official documentation says that port 5858 will be opened by default, but in actual tests, another port is opened by default. In order to attach to the process successfully, port 5858 is specified.

runelectron .Possible error handling

XXX \node_modules\electron\index.js:14 throw new Error(‘ electron failed to install correctly, Please delete node_modules/electron and try installing again, the problem is solved as follows:

Based on the code above, running electron. Will work fine, launch the window and use it.

But a re-run of NPM run start(i.e. Electron.) much later , even reported this error:

e:\vscode\Electron\WaterfullElectron\node_modules\electron\index.js:14
    throw new Error('Electron failed to install correctly, please delete node_modules/electron and try installing again')
    ^

Error: Electron failed to install correctly, please delete node_modules/electron and try installing again
    at getElectronPath (e:\vscode\Electron\WaterfullElectron\node_modules\electron\index.js:14:11)
    at Object.<anonymous> (e:\vscode\Electron\WaterfullElectron\node_modules\electron\index.js:18:18)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
    at Module.load (internal/modules/cjs/loader.js:811:32)
    at Function.Module._load (internal/modules/cjs/loader.js:723:14)
    at Module.require (internal/modules/cjs/loader.js:848:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (e:\vscode\Electron\WaterfullElectron\node_modules\electron\cli.js:3:16)
    at Module._compile (internal/modules/cjs/loader.js:955:30)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `electron .`
npm ERR! Exit status 1
npm ERR!
ging output above.
Copy the code

Node_modules \electron\index.js:14 error: path. TXT file does not exist.

At first, referring to the error “Electron failed to install correctly”, the basic steps are the same, but the execution of node install under the Electron project, The downloaded electron file does exist [although the download is stuck], switch the NPM package image source and run the download successfully.

But running run start is just as wrong.

Try to modify the Temp permission, re-download, etc.

Finally refer to Stack Overflow below Electron failed to install correctly, please delete node_modules/electron and try installing again. Could it be a conflict of versions? To solve the problem, manually download the Electron file and modify the path. TXT file.

Please do the following steps in order to solve the problem:

Create a file named path. TXT in node_modules\electron Folder.

Write electron. Exe in it. (The content of the path. TXT file is: electron.

Download electron package manualy. Maybe from: fossies.org/windows/www… (Download the electron zip file for your system that is displayed when you run Node install on node_Modules /electron, or download the corresponding system electron version directly. My is github.com/electron/el…).

Unpackage the electron files into node_modules\electron\dist Unpackage the electron files into node_modules\electron\dist

Run your start script (Run NPM Run start or YARN start again, Run successfully, open the Electron program)

reference

  • Electron official Document

  • Electron Introductory Tutorial 1 (Basic Installation of Electron, etc.)

  • Electron developing a cross-platform desktop application tutorial

Electron packager EXE electron packager

  • Debug the Electron main process using Visual Studio Code