Electron allows you to create desktop applications using pure JavaScript calling rich native APIs. You can think of it as a node.js variant that focuses on desktop applications rather than Web servers.

One. Preparation

  1. Install the node
  2. Install electon in the electron environment a. NPM command
npm i electron -g
or
npm i electron --save-dev
Copy the code
  1. Install electric-Packager, a tool for packaging electron applications, into various platform executables, not installation packages
npm i electron-packager -g
or
npm i electron-packager --save-dev
Copy the code
  1. Install the electron- Builder package into the installation package
npm i electron-builder -g
or
npm i electron-builder --save-dev
Copy the code

Create an application

To create a electron application, we only need three files. Index.html main.js package.json index.html is the page we want to display, main.js is the entry point for the application, package.json is the configuration file for the NPM project. A basic electron application generally has the following directory structure:

├─ download.txt └─ download.txt └─ download.txtCopy the code
  1. Open command line tools in that folder directory, and run NPM init
npm init
Copy the code

NPM will help you create a basic package.json file where the main field represents the application’s startup script and the start script executes the current package. Here is an example of package.json:

{
  "name": "your-app"."version": "0.1.0 from"."main": "main.js"."scripts": {
    "start": "electron ."}}Copy the code
  1. index.html
<! DOCTYPE html> <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge"</div> </body> </ HTML > </title> Document</title> </head> <body> </div>Copy the code
  1. Main.js Electron apps is developed using JavaScript, and its working principle and method are the same as node.js development. The electron module contains all the apis and functions provided by electron, and is introduced in the same way as the normal Node.js 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. Here is a main.js file that will open a window when the application is ready:

const { app, BrowserWindow } = require('electron'// Keep a global reference to the window object. Otherwise, the window object will be closed automatically when the JavaScript object is garbage collectedlet win

function createWindow() {// Create browser window. win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration:true}}) // load the index.html file win.loadFile('index.html') / / open the developer tools win. WebContents. OpenDevTools () / / when the window is closed, the event will be triggered. win.on('closed', () => {// Unreference the window object. If your application supports multiple Windows, // usually stores multiple window objects in an array. // In the meantime, you should delete the corresponding element. Win = null})} // Electron will call this function after initialization and when preparing // to create a browser window. // 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, most applications and their menu bar remain active unless the user explicitly exits with Cmd + Q.if(process.platform ! = ='darwin') {
    app.quit()
  }
})

app.on('activate', () => {// On macOS, when you click on the Dock icon and no other window opens, // usually a new window is created in the application.if(win === null) {createWindow()}}) // In this file, you can continue to 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
  1. After creating and initializing main.js,index.html, and package.json, you can run the NPM start command in the root directory of the current project to start the electon program you just wrote. When it starts, it looks like sauce

Electron -packager packages executable files

Let’s start by continuing with the project file above and simply adding a field to package.json. The basic pack commands for electron- Packager are:

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

Parameter Description:

  • Sourcedir: indicates the path of the project
  • Appname: indicates the application name
  • Platform: Determines which platform you want to build the application on (Windows, Mac, or Linux)
  • Arch: Deciding whether to use x86 or X64 or both architectures
  • Optional options: ElectronDemo –platform=win32 –arch=x64 –icon= Computer.ico –out=./out –app-version=0.0.1 –overwrite –ignore=node_modules or add code to package.json:
"scripts": {
    "package": ElectronDemo --platform=win32 --arch=x64 --icon=computer.ico --out=./out --app-version=0.0.1 --overwrite --ignore=node_modules"
  },
Copy the code

Then execute the NPM run package in the command line, we can see that.exe is generated in the out folder. Run the file and no error is reported, indicating that the package is successful.

electron-builder

4. Pack react, VUE projects with electron packager

  • When our project is complete, we execute a package command, such as my NPM run build, which generates the following structure under the build folder:

  • Json to add “homepage”: “./”. After running NPM run build, we should see the contents of this file.
  • With the contents visible in index.html, we create main.js and package.json files under the build folder. The contents of mian. At this point NPM Run Dist is successful

Five. Electron – Builder package installation package

Continue to use the same project files you used to create an app, main.js, index.html, and package.json

  1. Install the electron builder in the project
npm i electron-builder --save-dev
Copy the code
  1. Add this code to the package.json file:
"build": {
    "appId": "com.example.app"."mac": {
      "target": [// Target package type"dmg"."zip"]},"win": {
      "target": [// Target package type"nsis"."zip"]}},"scripts": {
    "dist": "electron-builder"
  },
Copy the code
  1. Execute NPM run dist on the command line and if things go well there will be a dist folder in the directory

The location of each operating system package is as follows:

  • macOS ~/Library/Caches/electron-builder
  • linux ~/.cache/electron-builder
  • windows %LOCALAPPDATA%\electron-builder\cache

A. Download the NSIS package at github.com/electron-us…

B. Download the WinCoDesign package at github.com/electron-us… Download the NSIS – Resources package at github.com/electron-us…

C. Create a new electron Builder Cache<br> in %LOCALAPPDATA% (c: Users\ wB-zy533658 \AppData\Local)

D. Decompress the downloaded ZIP to the directory in step 3, create a corresponding folder according to the error version, and move the file to the directory, as shown in the figure below:

  • OneClick is set to false
  • AllowToChangeInstallationDirectory set to true
"build": {
    "appId": "com.example.app"."mac": {
      "target": [
        "dmg"."zip"]."icon": "img.ico"
    },
    "win": {
      "target": [
        "nsis"."zip"]."icon": "img.ico"// Replace the icon generated on the desktop},"nsis": {
      "oneClick": false// Enable one-click installationfalse, can let the user click next, next, next form to install the program, iftrueWhen the user double-clicks the built program, the program will be automatically installed and opened, that is, one-click installation"allowToChangeInstallationDirectory": true// The installation directory can be changedtrueWhether to allow users to change the installation directory. The default value is no"createDesktopShortcut": true// Create a desktop icon"createStartMenuShortcut": true// Create a start menu icon"installerIcon": "test.ico"// Install the icon"uninstallerIcon": "xxx.ico"// Uninstall the icon"installerHeaderIcon": "xxx.ico"// Install header icon},"scripts": {
      "dist": "electron-builder"}}Copy the code

In the NPM Run Dist, let’s see what the effect is. We have configured our own icon in the installerIcon configuration TAB. In the image below, we can see that it has already taken effect

"build": {
    "appId": "com.example.app"."mac": {
      "target": [
        "dmg"."zip"]."icon": "img.ico"// Replace the generated icon},"win": {
      "target": [
        "nsis"."zip"]."icon": "img.ico"
    },
    "nsis": {
      "oneClick": false."allowToChangeInstallationDirectory": true."createDesktopShortcut": true."createStartMenuShortcut": true."installerIcon": "test.ico"}},Copy the code

This is the desktop icon that takes effect

Error in ectron-Builder packaging

At the end of the package there was an error message saying that an entry file ‘build/electron.js’ was not found

"build": {
    "appId": "com.example.app"."mac": {
      "target": [
        "dmg"."zip"]."icon": "img.ico"// Replace the generated icon},"win": {
      "target": [
        "nsis"."zip"]."icon": "img.ico"
    },
      "files": [
      "index.html"."main.js"."package.json"."build/electron.js"]},Copy the code